Example usage for org.apache.commons.lang StringUtils left

List of usage examples for org.apache.commons.lang StringUtils left

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils left.

Prototype

public static String left(String str, int len) 

Source Link

Document

Gets the leftmost len characters of a String.

Usage

From source file:net.bible.service.common.TitleSplitter.java

private String[] checkMaximumPartLength(String[] parts, int maximumLength) {
    for (int i = 0; i < parts.length; i++) {
        if (parts[i].length() > maximumLength) {
            parts[i] = StringUtils.left(parts[i], maximumLength);
        }/*from  ww  w  .ja v  a2  s.c  o  m*/
    }
    return parts;
}

From source file:net.sf.ipsedixit.core.impl.StringFieldHandler.java

/**
 * @param mutableField the {@link net.sf.ipsedixit.core.MutableField} containing a String field.
 * @return a random String value, constrained by any metadata that is present on the field.
 *//*from   ww w.jav  a  2 s .co  m*/
public String getValueFor(MutableField mutableField) {
    StringBuilder stringBuilder = new StringBuilder();
    StringMetaData stringMetaData = metaDataProvider.getMetaData(mutableField);

    int totalLength = stringMetaData.length();
    StringType stringType = stringMetaData.type();

    appendFieldNameIfRequired(stringBuilder, mutableField, stringType, totalLength);
    appendContainedStringIfRequired(stringBuilder, stringType, stringMetaData);
    stringBuilder.append(dataProvider.randomString(stringType, totalLength));

    return StringUtils.left(stringBuilder.toString(), totalLength);
}

From source file:com.intel.cosbench.exporter.ScriptsLogExporter.java

private void exportScriptLog(Writer writer, String logCtx, String driver) throws IOException {
    int idx = StringUtils.indexOf(logCtx, ";");
    if (idx < 0 || idx + 1 == logCtx.length())
        return;/* w  ww  . j  ava 2  s .  co  m*/
    String scriptName = StringUtils.left(logCtx, idx);
    String log = StringUtils.substring(logCtx, idx + 1);
    writer.write("-----------------");
    writer.write("-----------------");
    writer.write(" driver: " + driver + "  script: " + scriptName + ' ');
    writer.write("-----------------");
    writer.write("-----------------");
    writer.write('\n');
    writer.write(log);
}

From source file:com.googlecode.fascinator.common.MimeTypeUtil.java

/**
 * Print Exception in readable format//w  ww.j  av a2  s  . co m
 * 
 * @param e Exception
 * @return Readable version of Exception
 */
private static String toPrintable(Exception e) {
    String msg = e.getMessage();
    if (StringUtils.isAsciiPrintable(msg)) {
        return msg;
    }
    return StringUtils.left(msg.replaceAll("[^\\p{ASCII}\\n]", "."), 32);
}

From source file:com.tesora.dve.common.TestDataGenerator.java

protected Object getColumnValue(ColumnMetadata cm) {
    Object cv = null;//from  w ww .  ja  va2s .co  m
    Calendar cal = Calendar.getInstance();

    switch (cm.getDataType()) {
    case Types.BIT:
    case Types.BOOLEAN:
        cv = Boolean.TRUE;
        break;
    case Types.BIGINT:
        cv = Long.MAX_VALUE;
        break;
    case Types.CHAR:
    case Types.VARCHAR:
        cv = StringUtils.left(baseString, cm.getSize());
        break;
    case Types.SMALLINT:
        cv = Short.MAX_VALUE;
        break;
    case Types.TINYINT:
        cv = Byte.MAX_VALUE;
        break;
    case Types.INTEGER:
        cv = Integer.MAX_VALUE;
        break;
    case Types.DOUBLE:
        cv = new Double(1234.5678); // TODO need to handle s,p
        break;
    case Types.FLOAT:
        cv = new Float(123.56); // TODO need to handle s,p
        break;
    case Types.DECIMAL:
        cv = new BigDecimal("12345.6789"); // TODO need to handle s,p
        break;
    case Types.DATE:
        cal.setTimeInMillis(123456789);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cv = cal.getTime();
        break;
    case Types.TIMESTAMP:
        cal.setTimeInMillis(123456789);
        cv = cal.getTime();
        break;
    case Types.TIME:
        cv = new Time(123456789);
        break;
    default:
        break;
    }

    return cv;
}

From source file:com.netflix.simianarmy.aws.conformity.SimpleDBConformityClusterTracker.java

/** {@inheritDoc} */
@Override/*from   ww  w  . j a  va  2 s.co m*/
public void addOrUpdate(Cluster cluster) {
    List<ReplaceableAttribute> attrs = new ArrayList<ReplaceableAttribute>();
    Map<String, String> fieldToValueMap = cluster.getFieldToValueMap();
    for (Map.Entry<String, String> entry : fieldToValueMap.entrySet()) {
        attrs.add(new ReplaceableAttribute(entry.getKey(), StringUtils.left(entry.getValue(), MAX_ATTR_SIZE),
                true));
    }
    PutAttributesRequest putReqest = new PutAttributesRequest(domain, getSimpleDBItemName(cluster), attrs);
    LOGGER.debug(String.format("Saving cluster %s to SimpleDB domain %s", cluster.getName(), domain));
    this.simpleDBClient.putAttributes(putReqest);
    LOGGER.debug("Successfully saved.");
}

From source file:blog.javaclue.jcexchanger.StringElement.java

public byte[] getFormattedBytes() {
    if (value == null) {
        if (isNullable) {
            if (AppProperties.useNullIndicator()) {
                return ("Y" + getBlanks(length - 1)).getBytes();
            } else {
                return getLowValues(length);
            }//from   www . ja v a 2s  .c  o  m
        } else {
            return getBlanks(length).getBytes();
        }
    } else {
        String rtn_str = toString();
        if (isNullable && AppProperties.useNullIndicator()) {
            rtn_str = "N" + rtn_str;
        }
        return StringUtils.rightPad(StringUtils.left(rtn_str, length), length, ' ').getBytes();
    }
}

From source file:com.evolveum.midpoint.web.util.MidPointResourceStreamLocator.java

@Override
public IResourceNameIterator newResourceNameIterator(String path, Locale locale, String style, String variation,
        String extension, boolean strict) {
    String pathWithoutExtension = path;
    String ext = extension;//from www.  jav  a2  s. com
    if (ext == null && path != null) {
        String[] array = path.split("\\.");
        ext = array.length > 1 ? array[array.length - 1] : null;

        int extLength = ext != null ? ext.length() + 1 : 0;
        pathWithoutExtension = StringUtils.left(path, path.length() - extLength);
    }
    if (!containsIgnoreCase(EXTENSIONS, ext)) {
        return super.newResourceNameIterator(path, locale, style, variation, extension, strict);
    }

    List<String> extensions = new ArrayList<>();

    if (containsIgnoreCase(MIMIFIED_EXTENSIONS, ext) && Application.exists()
            && Application.get().getResourceSettings().getUseMinifiedResources()
            && !pathWithoutExtension.endsWith(".min")) {
        extensions.add("min." + ext);
    }

    extensions.add(ext);

    return new SimpleResourceNameIterator(pathWithoutExtension, extensions);
}

From source file:ar.sgt.resolver.filter.ResolverFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    log.trace("Entering filter processing");
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String path = req.getRequestURI();
    if (!req.getContextPath().isEmpty()) {
        path = StringUtils.removeStartIgnoreCase(path, req.getContextPath());
    }//from  ww  w. ja v a2  s .c  o m
    if (path.startsWith("//")) {
        path = path.substring(1);
    }
    if (this.excludePath != null) {
        String fp = StringUtils.left(path, path.indexOf("/", 1));
        if (this.excludePath.contains(fp)) {
            log.trace("Skip path {}", path);
            chain.doFilter(request, response);
            return;
        }
    }
    if (this.appendBackSlash) {
        if (!path.endsWith("/"))
            path = path + "/";
    }
    log.debug("Resolve path: {}", path);
    Rule rule = resolverConfig.findRule(path);
    if (rule != null) {
        log.debug("Found rule {} using processor {}", rule.getName() == null ? "Unnamed" : rule.getName(),
                rule.getProcessor());
        if (rule.getName() != null) {
            req.setAttribute(RuleConstant.CURRENT_RULE, rule.getName());
            req.setAttribute(RuleConstant.CURRENT_PATH, req.getRequestURI());
        }
        ResolverContext context = new ResolverContext(filterConfig.getServletContext(), req, resp,
                rule.parseParams(), req.getMethod());
        String redirect = null;
        if (rule.getRedirect() != null) {
            // check first if there is a named rule matching
            if (rule.getProcessor().equals(PermanentRedirectProcessor.class.getName())) {
                redirect = rule.getRedirect();
            } else {
                UrlReverse reverse = new UrlReverse(resolverConfig);
                try {
                    redirect = req.getContextPath() + reverse.resolve(rule.getRedirect());
                    log.trace("Using named rule {}", rule.getRedirect());
                } catch (ReverseException e) {
                    log.error(e.getMessage());
                    redirect = rule.getRedirect();
                } catch (RuleNotFoundException e) {
                    log.trace("Rule with name {} not found. Simple url redirect", rule.getRedirect());
                    redirect = rule.getRedirect();
                }
            }
        }
        ProcessorContext processorContext = new ProcessorContext(rule, redirect);
        Processor processor;
        try {
            processor = loadClass(rule.getProcessor());
            processor.process(processorContext, context);
        } catch (HttpError e) {
            log.debug("Handling HTTP ERROR {}", e.getHttpErrorCode());
            resp.sendError(e.getHttpErrorCode());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServletException(e);
        }
    } else {
        log.trace("No matching rule found");
        chain.doFilter(request, response);
    }
}

From source file:eu.uqasar.web.upload.FileUploadUtil.java

Path getNewFileName(FileUpload file, User user, boolean overwrite) throws IOException {
    Path target;/*from ww w .  j  ava2 s . co  m*/
    String uploadedFileFileName = file.getClientFileName();
    if (overwrite) {
        target = FileSystems.getDefault().getPath(getUserUploadFolder(user).toString(), uploadedFileFileName);
    } else {
        final String extensionPart = FilenameUtils.getExtension(uploadedFileFileName);
        final String extension = StringUtils.isEmpty(extensionPart) ? "" : "." + extensionPart;
        // we add a dot (".") before the UUID, so +1
        final int UUID_LENGTH = 1 + 36;
        // extension length is given out of extension length + the dot (".txt" == 4, no extension == 0)
        final int EXTENSION_LENGTH = extension.length();
        // MAX file name length is 255 - UUID part - Extension part
        final int MAX_BASE_FILENAME_LENGTH = 255 - UUID_LENGTH - EXTENSION_LENGTH;
        // shorten file name to no longer than max length, calculated above
        final String fileNameWithoutExtension = StringUtils
                .left(FilenameUtils.getBaseName(uploadedFileFileName), MAX_BASE_FILENAME_LENGTH);
        // generate new file name out of shortened base name + "." + UUID + any extension (including ".")
        final String targetFileName = String.format("%s.%s%s", fileNameWithoutExtension,
                UUID.randomUUID().toString(), extension);
        target = FileSystems.getDefault().getPath(getUserUploadFolder(user).toString(), targetFileName);
    }
    return target;
}