private String handleOperator(String param) {
   param = StringUtils.replaceChars(param, "()", "");
   String oldOperator = " ";
   int result = 0;
   String tmp = "";
   for (int i = 0; i < param.length(); i++) {
     String operator = "" + param.charAt(i);
     if (StringUtils.isNumeric(operator)) {
       tmp += param.charAt(i);
     }
     if (!StringUtils.isNumeric(operator) || i == param.length() - 1) {
       if (oldOperator.equals(" ")) {
         result += Integer.parseInt(tmp);
       } else if (oldOperator.equals("*")) {
         result *= Integer.parseInt(tmp);
       } else if (oldOperator.equals("-")) {
         result -= Integer.parseInt(tmp);
       } else if (oldOperator.equals("/")) {
         result /= Integer.parseInt(tmp);
       }
       tmp = "";
       oldOperator = operator;
     }
   }
   return String.valueOf(result);
 }
Ejemplo n.º 2
0
 public int getRatingAsInt() {
   int result = 0;
   try {
     result = Integer.parseInt(StringUtils.replaceChars(rating, "EP", ""));
   } catch (NumberFormatException nfe) {
   }
   return result;
 }
Ejemplo n.º 3
0
 /**
  * Search for a resource in the classpath. For example calling the method getResource(getClass(),
  * "myTestName/foo.txt") from the class org.sonar.Foo loads the file
  * $basedir/src/test/resources/org/sonar/Foo/myTestName/foo.txt
  *
  * @return the resource. Null if resource not found
  */
 public static File getResource(Class baseClass, String path) {
   String resourcePath = StringUtils.replaceChars(baseClass.getCanonicalName(), '.', '/');
   if (!path.startsWith("/")) {
     resourcePath += "/";
   }
   resourcePath += path;
   return getResource(resourcePath);
 }
Ejemplo n.º 4
0
 /**
  * Removes all control characters from passed in String.
  *
  * @param pkgId package id
  * @param input char input
  */
 protected static String sanitize(Long pkgId, String input) {
   if (StringUtils.containsNone(input, CONTROL_CHARS)) {
     return input;
   }
   if (log.isDebugEnabled()) {
     log.debug(
         "Package " + pkgId + " metadata contains control chars, cleanup required: " + input);
   }
   return StringUtils.replaceChars(input, CONTROL_CHARS, CONTROL_CHARS_REPLACEMENT);
 }
Ejemplo n.º 5
0
  /**
   * Set annotation preferences of users for a given project such as window size, annotation
   * layers,... reading from the file system.
   *
   * @param aUsername The {@link User} for whom we need to read the preference (preferences are
   *     stored per user)
   * @param aRepositoryService the repository service.
   * @param aAnnotationService the annotation service.
   * @param aBModel The {@link BratAnnotatorModel} that will be populated with preferences from the
   *     file
   * @param aMode the mode.
   * @throws BeansException hum?
   * @throws IOException hum?
   */
  public static void setAnnotationPreference(
      String aUsername,
      RepositoryService aRepositoryService,
      AnnotationService aAnnotationService,
      BratAnnotatorModel aBModel,
      Mode aMode)
      throws BeansException, IOException {
    AnnotationPreference preference = new AnnotationPreference();
    BeanWrapper wrapper = new BeanWrapperImpl(preference);
    // get annotation preference from file system
    try {
      Properties props = aRepositoryService.loadUserSettings(aUsername, aBModel.getProject());
      for (Entry<Object, Object> entry : props.entrySet()) {
        String property = entry.getKey().toString();
        int index = property.lastIndexOf(".");
        String propertyName = property.substring(index + 1);
        String mode = property.substring(0, index);
        if (wrapper.isWritableProperty(propertyName) && mode.equals(aMode.getName())) {
          if (AnnotationPreference.class.getDeclaredField(propertyName).getGenericType()
              instanceof ParameterizedType) {
            List<String> value =
                Arrays.asList(
                    StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
            if (!value.get(0).equals("")) {
              wrapper.setPropertyValue(propertyName, value);
            }
          } else {
            wrapper.setPropertyValue(propertyName, entry.getValue());
          }
        }
      }
      aBModel.setPreferences(preference);

      // Get tagset using the id, from the properties file
      aBModel.getAnnotationLayers().clear();
      if (preference.getAnnotationLayers() != null) {
        for (Long id : preference.getAnnotationLayers()) {
          aBModel.getAnnotationLayers().add(aAnnotationService.getLayer(id));
        }
      } else {
        // If no layer preferences are defined, then just assume all layers are enabled
        List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
        aBModel.setAnnotationLayers(layers);
      }
    }
    // no preference found
    catch (Exception e) {
      // If no layer preferences are defined, then just assume all layers are enabled
      List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
      aBModel.setAnnotationLayers(layers);
    }
  }
Ejemplo n.º 6
0
  /**
   * Turn SOLR date range into year range. E.g. [1940-01-01T00:00:00Z TO 1949-12-31T00:00:00Z] to
   * 1940-1949
   *
   * @param fieldValue
   * @return
   */
  private String substituteYearsForDates(String fieldValue) {
    String dateRange = URLDecoder.decode(fieldValue);
    String formattedDate = StringUtils.replaceChars(dateRange, "[]", "");
    String[] dates = formattedDate.split(" TO ");

    if (dates != null && dates.length > 1) {
      // grab just the year portions
      dateRange =
          StringUtils.substring(dates[0], 0, 4) + "-" + StringUtils.substring(dates[1], 0, 4);
    }

    return dateRange;
  }
Ejemplo n.º 7
0
  private String buildUri(ServerDetailsDTO conDetails, String filePath) {
    filePath = StringUtils.replaceChars(filePath, '\\', '/');

    StringBuilder sftpUri = new StringBuilder("sftp://").append(conDetails.getIp());
    if (conDetails.getPort() > 0) {
      sftpUri.append(':').append(conDetails.getPort());
    }

    if (!filePath.startsWith("/")) {
      sftpUri.append('/');
    }
    sftpUri.append(filePath);
    return sftpUri.toString();
  }
Ejemplo n.º 8
0
  /**
   * @see
   *     br.com.nordestefomento.jrimum.vallia.digitoverificador.AbstractDigitoVerificador#calcule(java.lang.String)
   */
  @Override
  public int calcule(String numero) throws IllegalArgumentException {

    int dv1 = 0;
    int dv2 = 0;

    boolean isFormatoValido = false;

    validacao:
    {
      if (StringUtils.isNotBlank(numero)) {

        isFormatoValido =
            (Pattern.matches(REGEX_CNPJ_DV, numero)
                || Pattern.matches(REGEX_CNPJ_DV_FORMATED, numero));

        if (isFormatoValido) {

          numero = StringUtils.replaceChars(numero, ".", "");
          numero = StringUtils.replaceChars(numero, "/", "");

          dv1 = calculeDigito(numero);
          dv2 = calculeDigito(numero + dv1);

          break validacao;
        }
      }

      throw new IllegalArgumentException(
          "O CNPJ [ "
              + numero
              + " ] deve conter apenas números, sendo eles no formato ##.###.###/#### ou ############ !");
    }

    return Integer.parseInt(dv1 + "" + dv2);
  }
Ejemplo n.º 9
0
  /**
   * Validates the filename and makes sure it is legal. It trims and splits and replaces bad
   * characters.
   *
   * @param filename
   * @return A validated name with annoying characters replaced.
   * @throws WikiException If the filename is not legal (e.g. empty)
   */
  static String validateFileName(String filename) throws WikiException {
    if (filename == null || filename.trim().length() == 0) {
      log.error("Empty file name given.");

      // the caller should catch the exception and use the exception text as an i18n key
      throw new WikiException("attach.empty.file");
    }

    //
    //  Should help with IE 5.22 on OSX
    //
    filename = filename.trim();

    // If file name ends with .jsp or .jspf, the user is being naughty!
    if (filename.toLowerCase().endsWith(".jsp") || filename.toLowerCase().endsWith(".jspf")) {
      log.info(
          "Attempt to upload a file with a .jsp/.jspf extension.  In certain cases this "
              + "can trigger unwanted security side effects, so we're preventing it.");
      //
      // the caller should catch the exception and use the exception text as an i18n key
      throw new WikiException("attach.unwanted.file");
    }

    //
    //  Some browser send the full path info with the filename, so we need
    //  to remove it here by simply splitting along slashes and then taking the path.
    //

    String[] splitpath = filename.split("[/\\\\]");
    filename = splitpath[splitpath.length - 1];

    //
    //  Remove any characters that might be a problem. Most
    //  importantly - characters that might stop processing
    //  of the URL.
    //
    filename = StringUtils.replaceChars(filename, "#?\"'", "____");

    return filename;
  }
Ejemplo n.º 10
0
  public Map dataModel() {
    if (dataModel == null) {
      dataModel = Maps.newHashMap();

      dataModel.put("package", StringUtils.replaceChars(CCGenerator.packagePath, "/", "."));
      dataModel.put("author", "yanghao");
      dataModel.put("date_now", new Date());

      dataModel.put("file_name", fileName);
      dataModel.put("pojo", pojo.getSimpleName());

      // 构造函数参数
      dataModel.put("constructor_params", Joiner.on(",").withKeyValueSeparator(" ").join(params));
      dataModel.put("constructor_params_size", params.size());
      dataModel.put("constructor_values", Joiner.on(",").join(params.values()));

      // hibernate的映射主键
      dataModel.put("pojo_id_type", pojoId.getSimpleName());
      dataModel.put("hibernate_query", query);
    }
    return dataModel;
  }
Ejemplo n.º 11
0
 protected String cleanContentId(String contentId) {
   return StringUtils.replaceChars(contentId, " .%-_", "");
 }
Ejemplo n.º 12
0
 private static String convertSlash(String path) {
   return StringUtils.replaceChars(path, '\\', '/');
 }
Ejemplo n.º 13
0
 protected void saveGrantsGovXml(
     ProposalDevelopmentDocument pdDoc,
     boolean formEntryFlag,
     XmlObject formObject,
     List<AttachmentData> attachmentList,
     List<S2sAppAttachments> attachmentLists)
     throws Exception {
   String loggingDirectory =
       KraServiceLocator.getService(ConfigurationService.class)
           .getPropertyValueAsString(Constants.PRINT_XML_DIRECTORY);
   String opportunityId = pdDoc.getDevelopmentProposal().getS2sOpportunity().getOpportunityId();
   String proposalnumber = pdDoc.getDevelopmentProposal().getProposalNumber();
   String exportDate =
       StringUtils.replaceChars(
           (pdDoc.getDevelopmentProposal().getUpdateTimestamp().toString()), ":", "_");
   exportDate = StringUtils.replaceChars(exportDate, " ", ".");
   if (grantsGovXmlDirectoryFile == null) {
     grantsGovXmlDirectoryFile = new File(loggingDirectory + proposalnumber);
   }
   File newgrantsGovXmlDirectoryFile = null;
   int suffix = 1;
   while (grantsGovXmlDirectoryFile.exists() && formEntryFlag) {
     grantsGovXmlDirectoryFile = new File(loggingDirectory + proposalnumber);
     String filename = String.valueOf(suffix);
     newgrantsGovXmlDirectoryFile = new File(loggingDirectory + proposalnumber + "-" + filename);
     if (!newgrantsGovXmlDirectoryFile.exists()) {
       grantsGovXmlDirectoryFile = newgrantsGovXmlDirectoryFile;
       break;
     }
     suffix++;
   }
   if (formEntryFlag) {
     grantsGovXmlDirectoryFile.mkdir();
   }
   pdDoc.setSaveXmlFolderName(grantsGovXmlDirectoryFile.getName());
   for (AttachmentData attachmentData : attachmentList) {
     File attachmentFile = new File(grantsGovXmlDirectoryFile, "Attachments");
     attachmentFile.mkdir();
     File attachedFile = new File(attachmentFile, attachmentData.getFileName());
     FileOutputStream output = new FileOutputStream(attachedFile);
     output.write(attachmentData.getContent());
     output.close();
   }
   for (S2sAppAttachments attAppAttachments : attachmentLists) {
     File attachmentFile = new File(grantsGovXmlDirectoryFile, "Attachments");
     attachmentFile.mkdir();
     AttachmentDataSource ads = getAttributeContent(pdDoc, attAppAttachments.getContentId());
     File attachedFile = new File(attachmentFile, ads.getFileName());
     FileOutputStream output = new FileOutputStream(attachedFile);
     output.write(getAttContent(pdDoc, attAppAttachments.getContentId()));
     output.close();
   }
   File xmlFile =
       new File(
           grantsGovXmlDirectoryFile,
           opportunityId + "." + proposalnumber + "." + exportDate + ".xml");
   BufferedWriter out = new BufferedWriter(new FileWriter(xmlFile));
   out.write(formObject.xmlText());
   out.close();
   ZipOutputStream zipOutputStream = null;
   FileOutputStream fileOutputStream = new FileOutputStream(grantsGovXmlDirectoryFile + ".zip");
   zipOutputStream = new ZipOutputStream(fileOutputStream);
   addFolderToZip("", grantsGovXmlDirectoryFile.getPath(), zipOutputStream);
   zipOutputStream.flush();
   zipOutputStream.close();
 }
 public static String pipeSeparatedGroupsToCommaSeparatedGroups(String pipeSeparated) {
   return StringUtils.replaceChars(pipeSeparated, DirectoryImpl.AUTO_ADD_GROUPS_SEPARATOR, ',');
 }
Ejemplo n.º 15
0
 /**
  * This returns the values as a , seperated string
  *
  * @param values
  * @return
  */
 public static final String getDvdFormAttributesAsString(final String values) {
   return StringUtils.replace(StringUtils.replaceChars(values, "[]", ""), ", ", ",");
 }
Ejemplo n.º 16
0
  /**
   * Indexes page using the given IndexWriter.
   *
   * @param page WikiPage
   * @param text Page text to index
   * @param writer The Lucene IndexWriter to use for indexing
   * @return the created index Document
   * @throws IOException If there's an indexing problem
   */
  protected Document luceneIndexPage(WikiPage page, String text, IndexWriter writer)
      throws IOException {
    if (log.isDebugEnabled()) log.debug("Indexing " + page.getName() + "...");

    // make a new, empty document
    Document doc = new Document();

    if (text == null) return doc;

    // Raw name is the keyword we'll use to refer to this document for updates.
    Field field = new Field(LUCENE_ID, page.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED);
    doc.add(field);

    // Body text.  It is stored in the doc for search contexts.
    field =
        new Field(
            LUCENE_PAGE_CONTENTS, text, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO);
    doc.add(field);

    // Allow searching by page name. Both beautified and raw
    String unTokenizedTitle =
        StringUtils.replaceChars(
            page.getName(), MarkupParser.PUNCTUATION_CHARS_ALLOWED, c_punctuationSpaces);

    field =
        new Field(
            LUCENE_PAGE_NAME,
            TextUtil.beautifyString(page.getName()) + " " + unTokenizedTitle,
            Field.Store.YES,
            Field.Index.ANALYZED,
            Field.TermVector.NO);
    doc.add(field);

    // Allow searching by authorname

    if (page.getAuthor() != null) {
      field =
          new Field(
              LUCENE_AUTHOR,
              page.getAuthor(),
              Field.Store.YES,
              Field.Index.ANALYZED,
              Field.TermVector.NO);
      doc.add(field);
    }

    // Now add the names of the attachments of this page
    try {
      Collection attachments = m_engine.getAttachmentManager().listAttachments(page);
      String attachmentNames = "";

      for (Iterator it = attachments.iterator(); it.hasNext(); ) {
        Attachment att = (Attachment) it.next();
        attachmentNames += att.getName() + ";";
      }
      field =
          new Field(
              LUCENE_ATTACHMENTS,
              attachmentNames,
              Field.Store.YES,
              Field.Index.ANALYZED,
              Field.TermVector.NO);
      doc.add(field);

    } catch (ProviderException e) {
      // Unable to read attachments
      log.error("Failed to get attachments for page", e);
    }
    writer.addDocument(doc);

    return doc;
  }