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

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

Introduction

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

Prototype

public static boolean isAsciiPrintable(final CharSequence cs) 

Source Link

Document

Checks if the CharSequence contains only ASCII printable characters.

null will return false .

Usage

From source file:com.crushpaper.AccountAttributeValidator.java

/** Returns true if the password is valid. */
public static boolean isPasswordValid(String value) {
    return value != null && value.length() >= 8 && value.length() <= 20 && StringUtils.isAsciiPrintable(value);
}

From source file:com.github.britter.beanvalidators.strings.ASCIIConstraintValidator.java

@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
    return value == null || StringUtils.isAsciiPrintable(value);
}

From source file:com.norconex.importer.parser.GenericDocumentParserFactoryTest.java

@Test
public void testIgnoringContentTypes() throws IOException, ImporterException {

    GenericDocumentParserFactory factory = new GenericDocumentParserFactory();
    factory.setIgnoredContentTypesRegex("application/pdf");
    ImporterMetadata metadata = new ImporterMetadata();

    ImporterConfig config = new ImporterConfig();
    config.setParserFactory(factory);/*from   w w  w . j  ava2  s.c om*/
    Importer importer = new Importer(config);
    ImporterDocument doc = importer
            .importDocument(TestUtil.getAlicePdfFile(), ContentType.PDF, null, metadata, "n/a").getDocument();

    try (InputStream is = doc.getContent()) {
        String output = IOUtils.toString(is).substring(0, 100);
        output = StringUtils.remove(output, '\n');
        Assert.assertTrue("Non-parsed output expected to be binary.", !StringUtils.isAsciiPrintable(output));
    }
}

From source file:com.comcast.viper.flume2storm.event.F2SEvent.java

/**
 * @see java.lang.Object#toString()// w  w  w .  java 2 s.  c  o m
 */
@Override
public String toString() {
    ToStringBuilder toStringBuilder = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
            .append("headers", headers);
    String bodyStr = StringUtils.toEncodedString(body, F2SEventFactory.DEFAULT_CHARACTER_SET);
    if (StringUtils.isAsciiPrintable(bodyStr)) {
        toStringBuilder.append("body", bodyStr);
    } else {
        toStringBuilder.append(Hex.encodeHexString(body));
    }
    return toStringBuilder.toString();
}

From source file:com.look.CreateUserServlet.java

/**
 * Processes post and adds user to database if successful
 * @param request/* w w  w  .ja  v a 2s  . c o  m*/
 * @param response 
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    stop = false;
    Connection conn = null;
    String message;
    try {
        conn = LookDatabaseUtils.getNewConnection();
    } catch (ClassNotFoundException | SQLException ex) {
        Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String repeatPassword = request.getParameter("repeatPassword");
    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    if (username == null) {
        message = "Please enter a username";
        stop(request, response, message);
    } else if (password == null) {
        message = "Please enter a password";
        stop(request, response, message);
    } else if (repeatPassword == null) {
        message = "Please enter your password again";
        stop(request, response, message);
    } else if (firstName == null) {
        message = "Please enter your first name";
        stop(request, response, message);
    } else if (lastName == null) {
        message = "Please enter your last name";
        stop(request, response, message);
    }

    if (username != null) {
        if (username.length() < 5) {
            message = "Username must be at least 5 characters";
            stop(request, response, message);
        }
        if (!StringUtils.isAlphanumeric(username)) {
            message = "Username must be alpha numeric";
            stop(request, response, message);
        }
    }

    try {
        PreparedStatement usernameStatement = conn
                .prepareStatement("SELECT * FROM users " + "WHERE username= ? ;");
        usernameStatement.setString(1, username);
        ResultSet r = usernameStatement.executeQuery();
        if (r.next()) {
            message = "The desired username already exists";
            stop(request, response, message);
        }
    } catch (SQLException ex) {
        Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (password != null) {
        if (password.length() < 8) {
            message = "Password must be at least 8 characters in length";
            stop(request, response, message);
        }
        if (!StringUtils.isAsciiPrintable(password)) {
            message = "Password has invalid characters. Please try again.";
            stop(request, response, message);
        }
        if (repeatPassword != null && !password.equals(repeatPassword)) {
            message = "Given passwords do not match. Try again.";
            stop(request, response, message);
        }
    }

    if (stop) {
        return;
    }

    try {
        String createUserSQL = "INSERT INTO users (user_id, username, pass, first_name, last_name) "
                + "VALUES (?, ?, PASSWORD(?), ?, ?);";
        PreparedStatement createUserStatement = conn.prepareStatement(createUserSQL);
        createUserStatement.setString(2, username);
        createUserStatement.setString(3, password);
        createUserStatement.setString(4, firstName);
        createUserStatement.setString(5, lastName);

        Random r = new Random();
        int user_id = 0;
        while (user_id == 0) {
            int temp_user_id = r.nextInt(10000000);
            ResultSet tempResult = conn.createStatement()
                    .executeQuery("SELECT * FROM users " + "WHERE user_id=" + temp_user_id + ";");
            if (!tempResult.next()) {
                user_id = temp_user_id;
            }
        }
        createUserStatement.setInt(1, user_id);

        createUserStatement.executeUpdate();
    } catch (SQLException ex) {
        Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    //it worked!!! forward to index jsp
    Logger.getLogger(CreateUserServlet.class.getName()).info("Account created");
    request.getSession().setAttribute("user", username);
    try {
        request.getSession().setAttribute("account_created", "yes");
        response.sendRedirect("thanks-join.jsp");
    } catch (IOException ex) {
        Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.netsteadfast.greenstep.action.CommonLoadUploadFileAction.java

private void loadData(File file) throws ServiceException, Exception {
    if (StringUtils.isBlank(this.oid)) {
        return;/*w  w  w.ja  v  a 2 s.  co  m*/
    }
    DefaultResult<SysUploadVO> result = this.sysUploadService.findForNoByteContent(this.oid);
    if (result.getValue() == null) {
        throw new ControllerException(result.getSystemMessage().getValue());
    }
    SysUploadVO uploadData = result.getValue();
    if (YesNo.YES.equals(uploadData.getIsFile())) {
        file = UploadSupportUtils.getRealFile(this.oid);
        if (!file.exists()) {
            return;
        }
        this.inputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
        this.filename = file.getName();
    } else {
        this.inputStream = new ByteArrayInputStream(UploadSupportUtils.getDataBytes(this.oid));
        this.filename = UploadSupportUtils.generateRealFileName(uploadData.getShowName());
    }
    if ("view".equals(this.type)) {
        if (file != null) {
            try {
                this.contentType = FSUtils.getMimeType(file);
            } catch (Exception e) {
                logger.warn(e.getMessage().toString());
            }
        } else {
            this.contentType = FSUtils.getMimeType(uploadData.getShowName());
        }
    }
    if (!StringUtils.isAsciiPrintable(result.getValue().getShowName())) {
        String userAgent = super.defaultString(super.getHttpServletRequest().getHeader("User-Agent"))
                .toLowerCase();
        if (userAgent.indexOf("firefox") == -1) { // for chrome or other browser.
            this.filename = URLEncoder.encode(result.getValue().getShowName(), Constants.BASE_ENCODING);
        }
        return;
    }
    this.filename = result.getValue().getShowName();
}

From source file:com.joyent.manta.config.ConfigContext.java

/**
 * Utility method for validating that the client-side encryption
 * configuration has been instantiated with valid settings.
 *
 * @param config configuration to test/*from   w  w  w.  ja v a 2s  . c  om*/
 * @param failureMessages list of messages to present the user for validation failures
 * @throws ConfigurationException thrown when validation fails
 */
static void encryptionSettings(final ConfigContext config, final List<String> failureMessages) {
    // KEY ID VALIDATIONS

    if (config.getEncryptionKeyId() == null) {
        failureMessages.add("Encryption key id must not be null");
    }
    if (config.getEncryptionKeyId() != null && StringUtils.isEmpty(config.getEncryptionKeyId())) {
        failureMessages.add("Encryption key id must not be empty");
    }
    if (config.getEncryptionKeyId() != null && StringUtils.containsWhitespace(config.getEncryptionKeyId())) {
        failureMessages.add("Encryption key id must not contain whitespace");
    }
    if (config.getEncryptionKeyId() != null && !StringUtils.isAsciiPrintable(config.getEncryptionKeyId())) {
        failureMessages.add(("Encryption key id must only contain printable ASCII characters"));
    }

    // AUTHENTICATION MODE VALIDATIONS

    if (config.getEncryptionAuthenticationMode() == null) {
        failureMessages.add("Encryption authentication mode must not be null");
    }

    // PERMIT UNENCRYPTED DOWNLOADS VALIDATIONS

    if (config.permitUnencryptedDownloads() == null) {
        failureMessages.add("Permit unencrypted downloads flag must not be null");
    }

    // PRIVATE KEY VALIDATIONS

    if (config.getEncryptionPrivateKeyPath() == null && config.getEncryptionPrivateKeyBytes() == null) {
        failureMessages.add("Both encryption private key path and private key bytes must not be null");
    }

    if (config.getEncryptionPrivateKeyPath() != null && config.getEncryptionPrivateKeyBytes() != null) {
        failureMessages.add("Both encryption private key path and private key bytes must "
                + "not be set. Choose one or the other.");
    }

    if (config.getEncryptionPrivateKeyPath() != null) {
        File keyFile = new File(config.getEncryptionPrivateKeyPath());

        if (!keyFile.exists()) {
            failureMessages.add(String.format("Key file couldn't be found at path: %s",
                    config.getEncryptionPrivateKeyPath()));
        } else if (!keyFile.canRead()) {
            failureMessages.add(String.format("Key file couldn't be read at path: %s",
                    config.getEncryptionPrivateKeyPath()));
        }
    }

    if (config.getEncryptionPrivateKeyBytes() != null) {
        if (config.getEncryptionPrivateKeyBytes().length == 0) {
            failureMessages.add("Encryption private key byte length must be greater than zero");
        }
    }

    // CIPHER ALGORITHM VALIDATIONS

    final String algorithm = config.getEncryptionAlgorithm();

    if (algorithm == null) {
        failureMessages.add("Encryption algorithm must not be null");
    }

    if (algorithm != null && StringUtils.isBlank(algorithm)) {
        failureMessages.add("Encryption algorithm must not be blank");
    }

    if (algorithm != null && !SupportedCiphersLookupMap.INSTANCE.containsKeyCaseInsensitive(algorithm)) {
        String availableAlgorithms = StringUtils.join(SupportedCiphersLookupMap.INSTANCE.keySet(), ", ");
        failureMessages.add(String.format(
                "Cipher algorithm [%s] was not found among " + "the list of supported algorithms [%s]",
                algorithm, availableAlgorithms));
    }
}

From source file:Anaphora_Resolution.ParseAllXMLDocuments.java

@SuppressWarnings("rawtypes")
public static ArrayList<List> preprocess(DocumentPreprocessor strarray) {
    ArrayList<List> Result = new ArrayList<List>();
    for (List<HasWord> sentence : strarray) {
        if (!StringUtils.isAsciiPrintable(sentence.toString())) {
            continue; // Removing non ASCII printable sentences
        }//from  w w  w .j  a  va 2s  .c  o m
        //string = StringEscapeUtils.escapeJava(string);
        //string = string.replaceAll("([^A-Za-z0-9])", "\\s$1");
        int nonwords_chars = 0;
        int words_chars = 0;
        for (HasWord hasword : sentence) {
            String next = hasword.toString();
            if ((next.length() > 30) || (next.matches("[^A-Za-z]")))
                nonwords_chars += next.length(); // Words too long or non alphabetical will be junk
            else
                words_chars += next.length();
        }
        if ((nonwords_chars / (nonwords_chars + words_chars)) > 0.5) // If more than 50% of the string is non-alphabetical, it is going to be junk
            continue; // Working on a character-basis because some sentences may contain a single, very long word
        if (sentence.size() > 100) {
            System.out.println("\tString longer than 100 words!\t" + sentence.toString());
            continue;
        }
        Result.add(sentence);
    }
    return Result;
}

From source file:com.crushpaper.Servlet.java

/** Returns the markdown for a help item with the specified name. */
private String getHelpMarkdown(String helpName) {
    // Basic validation.
    if (helpName == null || helpName.isEmpty() || helpName.length() > 50
            || !StringUtils.isAsciiPrintable(helpName)) {
        return null;
    }/*  w w w  . jav a2  s  .  com*/

    if (isInJar) {
        if (helpMarkdownMap.containsKey(helpName)) {
            return helpMarkdownMap.get(helpName);
        }
    }

    final String helpMarkeddown = getHelpMarkdownHelper(helpName);
    if (isInJar) {
        helpMarkdownMap.put(helpName, helpMarkeddown);
    }

    return helpMarkeddown;
}

From source file:org.kalypso.commons.databinding.validation.StringIsAsciiPrintableValidator.java

@Override
protected IStatus doValidate(final String value) throws CoreException {
    if (value != null && !StringUtils.isAsciiPrintable(value))
        fail();// w  w  w  . ja  va 2s  .com

    return ValidationStatus.ok();
}