Example usage for org.apache.commons.lang3 StringUtils replaceChars

List of usage examples for org.apache.commons.lang3 StringUtils replaceChars

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils replaceChars.

Prototype

public static String replaceChars(final String str, final String searchChars, String replaceChars) 

Source Link

Document

Replaces multiple characters in a String in one go.

Usage

From source file:com.commander4j.util.JUtility.java

public static String removePathSeparators(String path) {
    String result = path;/*  w w  w .java  2s  .c  o  m*/

    result = StringUtils.replaceChars(result, String.valueOf(":"), "_");
    result = StringUtils.replaceChars(result, String.valueOf("\\"), "_");
    result = StringUtils.replaceChars(result, String.valueOf("/"), "_");

    return result;
}

From source file:de.vandermeer.skb.datatool.commons.DataSet.java

/**
 * Returns the start of a key for key auto-generation
 * @param fs the file name/*  ww  w  . j a  v a 2s.  co  m*/
 * @param commonPath the common path of all file names
 * @return start of the key
 */
String calcKeyStart(FileSource fs, String commonPath) {
    //remove common path
    String ret = StringUtils.substringAfterLast(fs.getAbsoluteName(), commonPath + File.separator);

    //replace all path separators with key separators
    ret = StringUtils.replaceChars(ret, File.separatorChar, this.cs.getKeySeparator());

    //remove the last dot (".json")
    ret = StringUtils.substringBeforeLast(ret, ".");
    //remove the last dot (".entry") - the entry file extension
    ret = StringUtils.substringBeforeLast(ret, ".");

    //return the key plus a final separator
    return ret + this.cs.getKeySeparator();
}

From source file:com.sketchy.server.ImageUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {/*from   ww  w . j  ava 2s .c om*/

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(FileUtils.getTempDirectory());
            factory.setSizeThreshold(MAX_SIZE);

            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            List<FileItem> files = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : files) {
                String uploadFileName = fileItem.getName();
                if (StringUtils.isNotBlank(uploadFileName)) {
                    // Don't allow \\ in the filename, assume it's a directory separator and convert to "/"
                    // and take the filename after the last "/"
                    // This will fix the issue of Jetty not reading and serving files
                    // with "\" (%5C) characters 
                    // This also fixes the issue of IE sometimes sending the whole path 
                    // (depending on the security settings)
                    uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/");
                    if (StringUtils.contains(uploadFileName, "/")) {
                        uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/");
                    }

                    File uploadFile = HttpServer.getUploadFile(uploadFileName);
                    // make sure filename is actually in the upload directory
                    // we don't want any funny games
                    if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)) {
                        throw new RuntimeException("Can not upload File. Invalid directory!");
                    }

                    // if saved ok, then need to add the data file
                    SourceImageAttributes sourceImageAttributes = new SourceImageAttributes();
                    sourceImageAttributes.setImageName(uploadFileName);

                    File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename());
                    if (pngFile.exists()) {
                        throw new Exception(
                                "Can not Upload file. File '" + uploadFileName + "' already exists!");
                    }
                    File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename());

                    // Convert the image to a .PNG file
                    BufferedImage image = ImageUtils.loadImage(fileItem.getInputStream());
                    ImageUtils.saveImage(pngFile, image);

                    sourceImageAttributes.setWidth(image.getWidth());
                    sourceImageAttributes.setHeight(image.getHeight());

                    FileUtils.writeStringToFile(dataFile, sourceImageAttributes.toJson());
                    jsonServletResult.put("imageName", uploadFileName);
                }
            }
        }
    } catch (Exception e) {
        jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage());
    }
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(jsonServletResult.toJSONString());
}

From source file:com.epam.dlab.automation.helper.PropertiesResolver.java

public static void overlapProperty(Properties props, String propertyName, boolean isOptional) {
    String argName = StringUtils.replaceChars(propertyName, '_', '.').toLowerCase();
    String s = System.getProperty(argName, "");
    if (!s.isEmpty()) {
        props.setProperty(propertyName, s);
    }// w ww  .  j  a va2 s.  c o  m
    if (!isOptional && props.getProperty(propertyName, "").isEmpty()) {
        throw new IllegalArgumentException(
                "Missed required argument -D" + argName + " or property " + propertyName);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.transform.FuncGetObjectName.java

private static String resolveObjectName(String objectName, List<?> args) {
    String option = args.size() > 1 ? (String) args.get(1) : null;
    Options opt;/*from   w w w. jav a  2 s .  co m*/

    try {
        opt = StringUtils.isEmpty(option) ? Options.DEFAULT : Options.valueOf(option.toUpperCase());
    } catch (IllegalArgumentException exc) {
        opt = Options.DEFAULT;
    }

    switch (opt) {
    case FULL:
        break;
    case BEFORE:
        String sSymbol = args.size() > 2 ? (String) args.get(2) : null;
        if (StringUtils.isNotEmpty(sSymbol)) {
            objectName = StringUtils.substringBefore(objectName, sSymbol);
        }
        break;
    case AFTER:
        sSymbol = args.size() > 2 ? (String) args.get(2) : null;
        if (StringUtils.isNotEmpty(sSymbol)) {
            objectName = StringUtils.substringAfter(objectName, sSymbol);
        }
        break;
    case REPLACE:
        sSymbol = args.size() > 2 ? (String) args.get(2) : null;
        if (StringUtils.isNotEmpty(sSymbol)) {
            String rSymbol = args.size() > 3 ? (String) args.get(3) : null;
            objectName = StringUtils.replaceChars(objectName, sSymbol, rSymbol == null ? "" : rSymbol);
        }
        break;
    case SECTION:
        String idxStr = args.size() > 2 ? (String) args.get(2) : null;
        int idx;
        try {
            idx = Integer.parseInt(idxStr);
        } catch (Exception exc) {
            idx = -1;
        }

        if (idx >= 0) {
            sSymbol = args.size() > 3 ? (String) args.get(3) : null;
            String[] onTokens = StringUtils.split(objectName,
                    StringUtils.isEmpty(sSymbol) ? OBJ_NAME_TOKEN_DELIMITERS : sSymbol);
            objectName = idx < ArrayUtils.getLength(onTokens) ? onTokens[idx] : objectName;
        }
        break;
    case DEFAULT:
    default:
        idx = StringUtils.indexOfAny(objectName, OBJ_NAME_TOKEN_DELIMITERS);
        if (idx > 0) {
            objectName = StringUtils.substring(objectName, 0, idx);
        }
        break;
    }

    return objectName;
}

From source file:com.textocat.textokit.commons.consumer.AnnotationPerLineWriter.java

@Override
public void process(CAS cas) throws AnalysisEngineProcessException {
    String docUriStr = DocumentUtils.getDocumentUri(cas);
    if (docUriStr == null) {
        throw new IllegalStateException("Can't extract document URI");
    }/* w  w  w.j ava2  s  .  c om*/
    Path docUriPath = IoUtils.extractPathFromURI(docUriStr);
    if (docUriPath.isAbsolute()) {
        docUriPath = Paths.get("/").relativize(docUriPath);
    }
    Path outputPath = outputDir.resolve(docUriPath);
    outputPath = IoUtils.addExtension(outputPath, outputFileSuffix);
    try (PrintWriter out = IoUtils.openPrintWriter(outputPath.toFile())) {
        for (AnnotationFS anno : CasUtil.select(cas, targetType)) {
            String text = anno.getCoveredText();
            text = StringUtils.replaceChars(text, "\r\n", "  ");
            out.println(text);
        }
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
}

From source file:com.github.mbenson.privileged.weaver.FilesystemWeaver.java

/**
 * Clear the way by deleting classfiles woven with a different
 * {@link Policy}./* w  ww  . j ava2s .  c  o m*/
 * 
 * @throws NotFoundException
 */
public void prepare() throws NotFoundException {
    info("preparing %s; policy = %s", target, policy);
    final Set<File> toDelete = new TreeSet<File>();
    for (final Class<?> type : getDeclaringClasses(findPrivilegedMethods())) {
        final CtClass ctClass = classPool.get(type.getName());
        final String policyValue = toString(ctClass.getAttribute(generateName(POLICY_NAME)));
        if (policyValue == null || policyValue.equals(policy.name())) {
            continue;
        }
        debug("class %s previously woven with policy %s", type.getName(), policyValue);
        final File packageDir = new File(target,
                StringUtils.replaceChars(ctClass.getPackageName(), '.', File.separatorChar));

        // simple classname of outermost class, plus any inner classes:
        final String pattern = new StringBuilder(getOutermost(type).getSimpleName()).append("(\\$.+)??\\.class")
                .toString();

        debug("searching %s for pattern '%s'", packageDir.getAbsolutePath(), pattern);
        toDelete.addAll(FileUtils.listFiles(packageDir, new RegexFileFilter(pattern), null));
    }
    if (toDelete.isEmpty()) {
        return;
    }
    info("Deleting %s files...", toDelete.size());
    debug(toDelete.toString());
    for (File f : toDelete) {
        if (!f.delete()) {
            debug("Failed to delete %s", f);
        }
    }
}

From source file:gobblin.compaction.audit.KafkaAuditCountHttpClient.java

public Map<String, Long> fetch(String datasetName, long start, long end) throws IOException {
    String fullUrl = (this.baseUrl.endsWith("/") ? this.baseUrl : this.baseUrl + "/")
            + StringUtils.replaceChars(datasetName, '/', '.') + "?" + this.startQueryString + "=" + start + "&"
            + this.endQueryString + "=" + end;
    log.info("Full URL is " + fullUrl);
    String response = getHttpResponse(fullUrl);
    return parseResponse(fullUrl, response, datasetName);
}

From source file:com.haulmont.cuba.web.widgets.CubaTimeField.java

protected void updateTimeFormat() {
    String mask = StringUtils.replaceChars(timeFormat, "Hhmsa", "####U");
    placeholder = StringUtils.replaceChars(mask, "#U", "__");
    getState().mask = mask;//from w  w w  .j  av  a 2 s .c o m
}

From source file:com.commander4j.db.JDBPrinters.java

public String getExportRealPath() {
    String result = getExportPath();
    result = result.replace("{base_dir}", Common.base_dir);
    result = StringUtils.replaceChars(result, "\\", String.valueOf(File.separatorChar));
    result = StringUtils.replaceChars(result, "/", String.valueOf(File.separatorChar));
    logger.debug(result);/*from ww w  .j  a va 2 s  . c  o m*/
    return result;
}