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

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

Introduction

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

Prototype

public static boolean isAsciiPrintable(String str) 

Source Link

Document

Checks if the string contains only ASCII printable characters.

Usage

From source file:com.flexive.ejb.beans.configuration.DivisionConfigurationEngineBean.java

/**
 * {@inheritDoc}/*from  w  w w. j  a  va2 s  .c  o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeResourceValues(String keyPrefix) throws FxApplicationException {
    if (StringUtils.isBlank(keyPrefix))
        return;
    keyPrefix = keyPrefix.trim();
    if (keyPrefix.length() > 250)
        throw new FxApplicationException("ex.configuration.resource.key.tooLong", keyPrefix);
    if (!StringUtils.isAsciiPrintable(keyPrefix))
        throw new FxApplicationException("ex.configuration.resource.key.nonAscii", keyPrefix);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement("DELETE FROM " + TBL_RESOURCES + " WHERE RKEY LIKE ?");
        ps.setString(1, keyPrefix + "%");
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new FxApplicationException(e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(DivisionConfigurationEngine.class, con, ps);
    }
}

From source file:net.sourceforge.subsonic.service.TranscodingService.java

/**
 * Creates a transcoded input stream by interpreting the given command line string.
 * This includes the following:/*from w  w  w  .j  a va 2s.co  m*/
 * <ul>
 * <li>Splitting the command line string to an array.</li>
 * <li>Replacing occurrences of "%s" with the path of the given music file.</li>
 * <li>Replacing occurrences of "%t" with the title of the given music file.</li>
 * <li>Replacing occurrences of "%l" with the album name of the given music file.</li>
 * <li>Replacing occurrences of "%a" with the artist name of the given music file.</li>
 * <li>Replacing occurrcences of "%b" with the max bitrate.</li>
 * <li>Replacing occurrcences of "%o" with the video time offset (used for scrubbing).</li>
 * <li>Replacing occurrcences of "%w" with the video image width.</li>
 * <li>Replacing occurrcences of "%h" with the video image height.</li>
 * <li>Prepending the path of the transcoder directory if the transcoder is found there.</li>
 * </ul>
 *
 * @param command                  The command line string.
 * @param maxBitRate               The maximum bitrate to use. May not be {@code null}.
 * @param videoTranscodingSettings Parameters used when transcoding video. May be {@code null}.
 * @param mediaFile                The media file.
 * @param in                       Data to feed to the process.  May be {@code null}.  @return The newly created input stream.
 */
private TranscodeInputStream createTranscodeInputStream(String command, Integer maxBitRate,
        VideoTranscodingSettings videoTranscodingSettings, MediaFile mediaFile, InputStream in)
        throws IOException {

    String title = mediaFile.getTitle();
    String album = mediaFile.getAlbumName();
    String artist = mediaFile.getArtist();

    if (title == null) {
        title = "Unknown Song";
    }
    if (album == null) {
        title = "Unknown Album";
    }
    if (artist == null) {
        title = "Unknown Artist";
    }

    List<String> result = new LinkedList<String>(Arrays.asList(StringUtil.split(command)));
    result.set(0, getTranscodeDirectory().getPath() + File.separatorChar + result.get(0));

    File tmpFile = null;

    for (int i = 1; i < result.size(); i++) {
        String cmd = result.get(i);
        if (cmd.contains("%b")) {
            cmd = cmd.replace("%b", String.valueOf(maxBitRate));
        }
        if (cmd.contains("%t")) {
            cmd = cmd.replace("%t", title);
        }
        if (cmd.contains("%l")) {
            cmd = cmd.replace("%l", album);
        }
        if (cmd.contains("%a")) {
            cmd = cmd.replace("%a", artist);
        }
        if (cmd.contains("%o") && videoTranscodingSettings != null) {
            cmd = cmd.replace("%o", String.valueOf(videoTranscodingSettings.getTimeOffset()));
        }
        if (cmd.contains("%w") && videoTranscodingSettings != null) {
            cmd = cmd.replace("%w", String.valueOf(videoTranscodingSettings.getWidth()));
        }
        if (cmd.contains("%h") && videoTranscodingSettings != null) {
            cmd = cmd.replace("%h", String.valueOf(videoTranscodingSettings.getHeight()));
        }
        if (cmd.contains("%s")) {

            // Work-around for filename character encoding problem on Windows.
            // Create temporary file, and feed this to the transcoder.
            String path = mediaFile.getFile().getAbsolutePath();
            if (Util.isWindows() && !mediaFile.isVideo() && !StringUtils.isAsciiPrintable(path)) {
                tmpFile = File.createTempFile("subsonic", "." + FilenameUtils.getExtension(path));
                tmpFile.deleteOnExit();
                FileUtils.copyFile(new File(path), tmpFile);
                LOG.debug("Created tmp file: " + tmpFile);
                cmd = cmd.replace("%s", tmpFile.getPath());
            } else {
                cmd = cmd.replace("%s", path);
            }
        }

        result.set(i, cmd);
    }
    return new TranscodeInputStream(new ProcessBuilder(result), in, tmpFile);
}

From source file:net.sourceforge.vulcan.web.DefaultPreferencesStoreTest.java

public void testAscii() throws Exception {
    final String data = store.convertToString(prefs);
    assertTrue(StringUtils.isAsciiPrintable(data));
}

From source file:org.apache.wiki.providers.AbstractFileProvider.java

/**
 * Default validation, validates that key and value is ASCII <code>StringUtils.isAsciiPrintable()</code> and within lengths set up in jspwiki-custom.properties.
 * This can be overwritten by custom FileSystemProviders to validate additional properties
 * See https://issues.apache.org/jira/browse/JSPWIKI-856
 * @since 2.10.2/*from w w w .ja  v  a  2  s . c o m*/
 * @param customProperties the custom page properties being added
 */
protected void validateCustomPageProperties(Properties customProperties) throws IOException {
    // Default validation rules
    if (customProperties != null && !customProperties.isEmpty()) {
        if (customProperties.size() > MAX_PROPLIMIT) {
            throw new IOException("Too many custom properties. You are adding " + customProperties.size()
                    + ", but max limit is " + MAX_PROPLIMIT);
        }
        Enumeration propertyNames = customProperties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String key = (String) propertyNames.nextElement();
            String value = (String) customProperties.get(key);
            if (key != null) {
                if (key.length() > MAX_PROPKEYLENGTH) {
                    throw new IOException("Custom property key " + key + " is too long. Max allowed length is "
                            + MAX_PROPKEYLENGTH);
                }
                if (!StringUtils.isAsciiPrintable(key)) {
                    throw new IOException("Custom property key " + key + " is not simple ASCII!");
                }
            }
            if (value != null) {
                if (value.length() > MAX_PROPVALUELENGTH) {
                    throw new IOException("Custom property key " + key + " has value that is too long. Value="
                            + value + ". Max allowed length is " + MAX_PROPVALUELENGTH);
                }
                if (!StringUtils.isAsciiPrintable(value)) {
                    throw new IOException("Custom property key " + key
                            + " has value that is not simple ASCII! Value=" + value);
                }
            }
        }
    }
}

From source file:org.cesecore.certificates.certificate.CertificateCreateSessionBean.java

@Override
public CertificateResponseMessage createCertificate(final AuthenticationToken admin,
        final EndEntityInformation endEntityInformation, final CA ca, final RequestMessage req,
        final Class<? extends ResponseMessage> responseClass, CertificateGenerationParams certGenParams,
        final long updateTime)
        throws CryptoTokenOfflineException, SignRequestSignatureException, IllegalKeyException,
        IllegalNameException, CustomCertificateSerialNumberException, CertificateCreateException,
        CertificateRevokeException, CertificateSerialNumberException, AuthorizationDeniedException,
        IllegalValidityException, CAOfflineException, InvalidAlgorithmException, CertificateExtensionException {
    if (log.isTraceEnabled()) {
        log.trace(">createCertificate(IRequestMessage, CA)");
    }/*  w w w  .jav  a  2s  . c  o  m*/
    CertificateResponseMessage ret = null;
    try {
        final CAToken catoken = ca.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenManagementSession.getCryptoToken(catoken.getCryptoTokenId());
        final String alias = catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        // See if we need some key material to decrypt request
        if (req.requireKeyInfo()) {
            // You go figure...scep encrypts message with the public CA-cert
            req.setKeyInfo(ca.getCACertificate(), cryptoToken.getPrivateKey(alias),
                    cryptoToken.getEncProviderName());
        }
        // Verify the request
        final PublicKey reqpk;
        try {
            if (!req.verify()) {
                throw new SignRequestSignatureException(
                        intres.getLocalizedMessage("createcert.popverificationfailed"));
            }
            reqpk = req.getRequestPublicKey();
            if (reqpk == null) {
                final String msg = intres.getLocalizedMessage("createcert.nokeyinrequest");
                throw new InvalidKeyException(msg);
            }
        } catch (InvalidKeyException e) {
            // If we get an invalid key exception here, we should throw an IllegalKeyException to the caller
            // The catch of InvalidKeyException in the end of this method, catches error from the CA crypto token
            throw new IllegalKeyException(e);
        }

        final Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
        final Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
        final Extensions exts = req.getRequestExtensions(); // Optionally requested extensions
        int keyusage = -1;
        if (exts != null) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request");
            }
            final Extension ext = exts.getExtension(Extension.keyUsage);
            if (ext != null) {
                final ASN1OctetString os = ext.getExtnValue();
                DERBitString bs;
                try {
                    bs = new DERBitString(os.getEncoded());
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.");
                }
                keyusage = bs.intValue();
                if (log.isDebugEnabled()) {
                    log.debug("We have a key usage request extension: " + keyusage);
                }
            }
        }
        String sequence = null;
        byte[] ki = req.getRequestKeyInfo();
        // CVC sequence is only 5 characters, don't fill with a lot of garbage here, it must be a readable string
        if ((ki != null) && (ki.length > 0) && (ki.length < 10)) {
            final String str = new String(ki);
            // A cvc sequence must be ascii printable, otherwise it's some binary data
            if (StringUtils.isAsciiPrintable(str)) {
                sequence = new String(ki);
            }
        }

        CertificateDataWrapper certWrapper = createCertificate(admin, endEntityInformation, ca, req, reqpk,
                keyusage, notBefore, notAfter, exts, sequence, certGenParams, updateTime);
        // Create the response message with all nonces and checks etc
        ret = ResponseMessageUtils.createResponseMessage(responseClass, req, ca.getCertificateChain(),
                cryptoToken.getPrivateKey(alias), cryptoToken.getEncProviderName());
        ResponseStatus status = ResponseStatus.SUCCESS;
        FailInfo failInfo = null;
        String failText = null;
        if ((certWrapper == null) && (status == ResponseStatus.SUCCESS)) {
            status = ResponseStatus.FAILURE;
            failInfo = FailInfo.BAD_REQUEST;
        } else {
            ret.setCertificate(certWrapper.getCertificate());
            ret.setCACert(ca.getCACertificate());
            ret.setBase64CertData(certWrapper.getBase64CertData());
            ret.setCertificateData(certWrapper.getCertificateData());
        }
        ret.setStatus(status);
        if (failInfo != null) {
            ret.setFailInfo(failInfo);
            ret.setFailText(failText);
        }
        ret.create();
    } catch (InvalidKeyException e) {
        throw new CertificateCreateException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateCreateException(e);
    } catch (NoSuchProviderException e) {
        throw new CertificateCreateException(e);
    } catch (CertificateEncodingException e) {
        throw new CertificateCreateException(e);
    } catch (CRLException e) {
        throw new CertificateCreateException(e);
    }

    if (log.isTraceEnabled()) {
        log.trace("<createCertificate(IRequestMessage, CA)");
    }
    return ret;
}

From source file:org.cesecore.util.StringTools.java

/**
 * Takes input and converts to Base64 on the format "B64:<base64 endoced string>", if the string is not null or empty.
 * //  w  w w .  j a  v  a 2 s .co  m
 * @param s String to base64 encode
 * @param dontEncodeAsciiPrintable if the String is made up of pure ASCII printable characters, we will not B64 encode it
 * @return Base64 encoded string, or original string if it was null or empty
 */
public static String putBase64String(final String s, boolean dontEncodeAsciiPrintable) {
    if (StringUtils.isEmpty(s)) {
        return s;
    }
    if (s.startsWith("B64:")) {
        // Only encode once
        return s;
    }
    if (dontEncodeAsciiPrintable && StringUtils.isAsciiPrintable(s)) {
        return s;
    }
    String n = null;
    try {
        // Since we used getBytes(s, "UTF-8") in this method, we must use UTF-8 when doing the reverse in another method
        n = "B64:" + new String(Base64.encode(s.getBytes("UTF-8"), false));
    } catch (UnsupportedEncodingException e) {
        // Do nothing
        n = s;
    }
    return n;

}

From source file:org.codelibs.fess.helper.QueryHelper.java

protected void appendQueryValue(final StringBuilder buf, final String query, final boolean useBigram) {
    // check reserved
    boolean reserved = false;
    for (final String element : Constants.RESERVED) {
        if (element.equals(query)) {
            reserved = true;/*  www .ja  v a2s . c  o m*/
            break;
        }
    }

    if (reserved) {
        buf.append('\\');
        buf.append(query);
        return;
    }

    String value = query;
    if (useBigram && value.length() == 1 && !StringUtils.isAsciiPrintable(value)) {
        // if using bigram, add ?
        value = value + '?';
    }

    String fuzzyValue = null;
    String proximityValue = null;
    String caretValue = null;
    final int tildePos = value.lastIndexOf('~');
    final int caretPos = value.indexOf('^');
    if (tildePos > caretPos) {
        if (tildePos > 0) {
            final String tildeValue = value.substring(tildePos);
            if (tildeValue.length() > 1) {
                final StringBuilder buf1 = new StringBuilder();
                final StringBuilder buf2 = new StringBuilder();
                boolean isComma = false;
                for (int i = 1; i < tildeValue.length(); i++) {
                    final char c = tildeValue.charAt(i);
                    if (c >= '0' && c <= '9') {
                        if (isComma) {
                            buf2.append(c);
                        } else {
                            buf1.append(c);
                        }
                    } else if (c == '.') {
                        if (isComma) {
                            break;
                        } else {
                            isComma = true;
                        }
                    } else {
                        break;
                    }
                }
                if (buf1.length() == 0) {
                    fuzzyValue = "~";
                } else {
                    final int intValue = Integer.parseInt(buf1.toString());
                    if (intValue <= 0) {
                        // fuzzy
                        buf1.append('.').append(buf2.toString());
                        fuzzyValue = '~' + buf1.toString();
                    } else {
                        // proximity
                        proximityValue = '~' + Integer.toString(intValue);
                    }
                }
            } else {
                fuzzyValue = "~";
            }

            value = value.substring(0, tildePos);
        }
    } else {
        if (caretPos > 0) {
            caretValue = value.substring(caretPos);
            value = value.substring(0, caretPos);
        }
    }
    if (value.startsWith("[") && value.endsWith("]")) {
        appendRangeQueryValue(buf, value, '[', ']');
    } else if (value.startsWith("{") && value.endsWith("}")) {
        // TODO function
        appendRangeQueryValue(buf, value, '{', '}');
    } else {
        if (proximityValue == null) {
            buf.append(QueryUtil.escapeValue(value));
        } else {
            buf.append('"').append(QueryUtil.escapeValue(value)).append('"');
        }
    }

    if (fuzzyValue != null) {
        buf.append(fuzzyValue);
    } else if (proximityValue != null) {
        buf.append(proximityValue);
    } else if (caretValue != null) {
        buf.append(caretValue);
    }
}

From source file:org.eclipse.leshan.server.demo.servlet.log.CoapMessage.java

private CoapMessage(boolean incoming, Type type, int mId, String token, OptionSet options, byte[] payload) {
    this.incoming = incoming;
    this.timestamp = System.currentTimeMillis();
    this.type = type.toString();
    this.mId = mId;
    this.token = token;

    if (options != null) {
        List<Option> opts = options.asSortedList();
        if (!opts.isEmpty()) {
            Map<String, List<String>> optMap = new HashMap<>();
            for (Option opt : opts) {
                String strOption = OptionNumberRegistry.toString(opt.getNumber());
                List<String> values = optMap.get(strOption);
                if (values == null) {
                    values = new ArrayList<>();
                    optMap.put(strOption, values);
                }/* w w  w  . j a  va2 s  .co m*/
                values.add(opt.toValueString());
            }

            StringBuilder builder = new StringBuilder();
            for (Entry<String, List<String>> e : optMap.entrySet()) {
                if (builder.length() > 0) {
                    builder.append(" - ");
                }
                builder.append(e.getKey()).append(": ").append(StringUtils.join(e.getValue(), ", "));
            }
            this.options = builder.toString();

        }
    }
    if (payload != null && payload.length > 0) {
        String strPayload = new String(payload, Charsets.UTF_8);
        if (StringUtils.isAsciiPrintable(strPayload)) {
            this.payload = strPayload;
        } else {
            this.payload = "Hex:" + Hex.encodeHexString(payload);
        }
    }
}

From source file:org.eclipse.leshan.standalone.servlet.log.CoapMessage.java

private CoapMessage(boolean incoming, Type type, int mId, String token, OptionSet options, byte[] payload) {
    this.incoming = incoming;
    this.timestamp = System.currentTimeMillis();
    this.type = type.toString();
    this.mId = mId;
    this.token = token;

    if (options != null) {
        List<Option> opts = options.asSortedList();
        if (!opts.isEmpty()) {
            Map<String, List<String>> optMap = new HashMap<>();
            for (Option opt : opts) {
                String strOption = OptionNumberRegistry.toString(opt.getNumber());
                List<String> values = optMap.get(strOption);
                if (values == null) {
                    values = new ArrayList<>();
                    optMap.put(strOption, values);
                }//from  w w  w .j a  va 2  s  .  c o m
                switch (opt.getNumber()) {
                case OptionNumberRegistry.CONTENT_FORMAT:
                    values.add(String.valueOf(opt.getIntegerValue()));
                    break;
                default:
                    values.add(opt.getStringValue());
                }
            }

            StringBuilder builder = new StringBuilder();
            for (Entry<String, List<String>> e : optMap.entrySet()) {
                if (builder.length() > 0) {
                    builder.append(" - ");
                }
                builder.append(e.getKey()).append(": ").append(StringUtils.join(e.getValue(), ", "));
            }
            this.options = builder.toString();

        }
    }
    if (payload != null && payload.length > 0) {
        String strPayload = new String(payload, Charsets.UTF_8);
        if (StringUtils.isAsciiPrintable(strPayload)) {
            this.payload = strPayload;
        } else {
            this.payload = "Hex:" + Hex.encodeHexString(payload);
        }
    }
}

From source file:org.eclipse.wb.tests.designer.core.util.base64.Base64UtilsTest.java

public void test_encodeString() throws Exception {
    String encodedString = Base64Utils.encode(UNENCODED_STRING);
    assertEquals(ENCODED_STRING, encodedString);
    assertTrue(StringUtils.isAsciiPrintable(encodedString));
}