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

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

Introduction

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

Prototype

public static boolean isAlphanumeric(final CharSequence cs) 

Source Link

Document

Checks if the CharSequence contains only Unicode letters or digits.

null will return false .

Usage

From source file:jongo.config.JongoConfiguration.java

/**
 * From the given properties object, load the the different {@link jongo.config.DatabaseConfiguration}.
 * @param prop an instance of {@link java.util.Properties} with the properties from the file.
 * @return a list of {@link jongo.config.DatabaseConfiguration}
 * @throws StartupException if we're unable to load a {@link jongo.config.DatabaseConfiguration}.
 *///from   w  w  w  .jav a  2  s  .c o m
private static List<DatabaseConfiguration> getDatabaseConfigurations(final Properties prop)
        throws StartupException {
    String databaseList = prop.getProperty(p_name_jongo_database_list);
    if (databaseList == null) {
        throw new StartupException("Failed to read list of aliases " + p_name_jongo_database_list, demo);
    }
    final String[] names = databaseList.split(",");
    List<DatabaseConfiguration> databases = new ArrayList<DatabaseConfiguration>(names.length);
    for (String name : names) {
        name = name.trim();
        if (StringUtils.isAlphanumeric(name)) {
            DatabaseConfiguration c = generateDatabaseConfiguration(prop, name);
            databases.add(c);
        } else {
            l.warn("Database name {} is invalid. Continuing without it.", name);
        }
    }
    return databases;
}

From source file:ezbake.deployer.utilities.YamlManifestFileReader.java

private void validateManifest(ArtifactManifest artifactManifest) throws IllegalStateException {
    Preconditions.checkState(artifactManifest.getApplicationInfo().isSetServiceId(),
            getServiceIdName(artifactManifest) + " is expected to be set");
    Preconditions.checkState(StringUtils.isAlphanumeric(getServiceId(artifactManifest)),
            getServiceIdName(artifactManifest) + " must be alphanumeric: " + getServiceId(artifactManifest));
    Preconditions.checkState(artifactManifest.isSetArtifactType(), "ArtifactType is expected to be set");
    Preconditions.checkState(artifactManifest.getApplicationInfo().isSetSecurityId(),
            "SecurityId is expected to be set");
}

From source file:ch.cyberduck.core.Archive.java

/**
 * Escape blank/*from   www. j a  va  2s.co m*/
 *
 * @param path Filename
 * @return Escaped whitespace in path
 */
protected String escape(final String path) {
    final StringBuilder escaped = new StringBuilder();
    for (char c : path.toCharArray()) {
        if (StringUtils.isAlphanumeric(String.valueOf(c)) || c == Path.DELIMITER) {
            escaped.append(c);
        } else {
            escaped.append("\\").append(c);
        }
    }
    return escaped.toString();
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

@FXML
public void initialize() {
    this.rootItem = new TreeItem<>(new TreeNode("[root]"));
    this.root.setRoot(this.rootItem);
    this.root.setCellFactory(new TreeCellFactory<>(node -> {
        if (node.getParent() == null) {
            ContextMenu export = new ContextMenu();

            MenuItem exportItem = new MenuItem("Export");

            export.setOnAction(e -> {
                File file = messageHandler.chooseFile().withInitialDirectory(new File("."))
                        .withTitle(Message.GENERIC_CHOOSE_EXPORT_LOCATION_JAR.format())
                        .withExtensionFilter(new FileFilter(Message.FILETYPE_JAVA_ARCHIVE.format(), "*.jar"),
                                true)//  w ww  .  j  a va  2 s . c  o  m
                        .promptSave();

                OpenedFile openedFile = (OpenedFile) node.getMetadata().get(OpenedFile.OPENED_FILE);

                Map<String, byte[]> clone = new HashMap<>(openedFile.getContents());

                backgroundTaskHelper.submit(
                        new BackgroundTask(Message.TASK_SAVING_FILE.format(node.getDisplayName()), true, () -> {
                            try {
                                if (!file.exists()) {
                                    if (!file.createNewFile()) {
                                        throw new IOException("Could not create export file");
                                    }
                                }

                                try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                                        new FileOutputStream(file))) {
                                    for (Map.Entry<String, byte[]> ent : clone.entrySet()) {
                                        ZipEntry zipEntry = new ZipEntry(ent.getKey());
                                        zipOutputStream.putNextEntry(zipEntry);
                                        zipOutputStream.write(ent.getValue());
                                        zipOutputStream.closeEntry();
                                    }
                                }

                                messageHandler.handleMessage(Message.GENERIC_EXPORTED.format());
                            } catch (IOException ex) {
                                messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), ex);
                            }
                        }));
            });

            export.getItems().add(exportItem);
            return export;
        }
        return null;
    }));

    root.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
        if (event.getCode() == KeyCode.ENTER) {
            TreeItem<TreeNode> selected = this.root.getSelectionModel().getSelectedItem();
            if (selected != null) {
                if (selected.getChildren().size() != 0) {
                    selected.setExpanded(!selected.isExpanded());
                } else {
                    getParentController().getAllFilesViewerController().handleClick(selected.getValue());
                }
            }
        }
    });

    Tooltip tooltip = new Tooltip();
    StringBuilder search = new StringBuilder();

    List<TreeItem<TreeNode>> searchContext = new ArrayList<>();
    AtomicInteger searchIndex = new AtomicInteger();

    root.focusedProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue) {
            tooltip.hide();
            search.setLength(0);
        }
    });

    root.boundsInLocalProperty().addListener((observable, oldValue, newValue) -> {
        Bounds bounds = root.localToScreen(newValue);
        tooltip.setAnchorX(bounds.getMinX());
        tooltip.setAnchorY(bounds.getMinY());
    });

    root.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (tooltip.isShowing() && event.getCode() == KeyCode.UP) {
            if (searchIndex.decrementAndGet() < 0) {
                searchIndex.set(searchContext.size() - 1);
            }
        } else if (tooltip.isShowing() && event.getCode() == KeyCode.DOWN) {
            if (searchIndex.incrementAndGet() >= searchContext.size()) {
                searchIndex.set(0);
            }
        } else {
            return;
        }
        event.consume();

        root.scrollTo(root.getRow(searchContext.get(searchIndex.get())));
        root.getSelectionModel().select(searchContext.get(searchIndex.get()));
    });

    root.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (event.getCharacter().charAt(0) == '\b') {
            if (search.length() > 0) {
                search.setLength(search.length() - 1);
            }
        } else if (event.getCharacter().charAt(0) == '\u001B') { //esc
            tooltip.hide();
            search.setLength(0);
            return;
        } else if (search.length() > 0
                || (search.length() == 0 && StringUtils.isAlphanumeric(event.getCharacter()))) {
            search.append(event.getCharacter());
            if (!tooltip.isShowing()) {
                tooltip.show(root.getScene().getWindow());
            }
        }

        if (!tooltip.isShowing())
            return;

        String str = search.toString();
        tooltip.setText("Search for: " + str);

        searchContext.clear();

        ArrayDeque<TreeItem<TreeNode>> deque = new ArrayDeque<>();
        deque.addAll(rootItem.getChildren());

        while (!deque.isEmpty()) {
            TreeItem<TreeNode> item = deque.poll();
            if (item.getValue().getDisplayName().contains(str)) {
                searchContext.add(item);
            }
            if (item.isExpanded() && item.getChildren().size() > 0)
                deque.addAll(item.getChildren());
        }

        searchIndex.set(0);
        if (searchContext.size() > 0) {
            root.scrollTo(root.getRow(searchContext.get(0)));
            root.getSelectionModel().select(searchContext.get(0));
        }
    });

    openedFileController.loadedFiles().addListener((MapChangeListener<String, OpenedFile>) change -> {
        if (change.getValueAdded() != null) {
            updateTree(change.getValueAdded());
        }
        if (change.getValueRemoved() != null) {
            this.rootItem.getChildren()
                    .removeIf(ti -> ti.getValue().equals(change.getValueRemoved().getRoot()));
        }
    });
}

From source file:com.look.UploadPostServlet.java

/***************************************************************************
 * Processes request data and saves into instance variables
 * @param request HttpServletRequest from client
 * @return True if successfully handled, false otherwise
 *//*w w  w . j  a  v  a  2 s.co  m*/
private boolean handleRequest(HttpServletRequest request) {
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            boolean success = true;
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String filename = item.getName();
                    if (filename.equals("")) {
                        //only update responseMessage if there isn't one yet
                        if (responseMessage.equals("")) {
                            responseMessage = "Please choose an image";
                        }
                        success = false;
                    }
                    String clientFileName = FilenameUtils.getName("TEMP_" + item.getName().replaceAll(" ", ""));

                    imageExtension = FilenameUtils.getExtension(clientFileName);
                    imageURL = clientFileName + "." + imageExtension;
                    fileContent = item.getInputStream();
                } else {
                    String fieldName = item.getFieldName();
                    String value = item.getString();
                    //only title is required
                    if (value.equals("") && (fieldName.equals("title"))) {
                        responseMessage = "Please enter a title";
                        success = false;
                    }
                    switch (fieldName) {
                    case TITLE_FIELD_NAME:
                        title = value;
                        break;
                    case DESCRIPTION_FIELD_NAME:
                        description = value;
                        break;
                    case TAGS_FIELD_NAME:
                        tags = value;
                        if (!tags.equals("")) {
                            tagList = new LinkedList<>(Arrays.asList(tags.split(" ")));
                            for (int i = 0; i < tagList.size(); i++) {
                                String tag = tagList.get(i);
                                if (tag.charAt(0) != '#') {
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must begin with #";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else if (!StringUtils.isAlphanumeric(tag.substring(1))) {
                                    log.info(tag.substring(1));
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must only contain numbers and letters";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else if (tag.length() > 20) {
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must be 20 characters or less";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else {
                                    //tag is valid, remove the '#' for storage
                                    tagList.set(i, tag.substring(1));
                                }
                            }
                        }
                        //now have list of alphanumeric tags of 20 chars or less
                        break;
                    }
                }
            }
            if (!success) {
                return false;
            }
        } catch (FileUploadException | IOException ex) {
            Logger.getLogger(UploadPostServlet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        request.setAttribute("message", "File upload request not found");
        return false;
    }

    return true;
}

From source file:com.xpn.xwiki.util.Util.java

public static boolean isAlphaNumeric(String text) {
    return StringUtils.isAlphanumeric(text.replace('-', 'a').replace('.', 'a'));
}

From source file:nz.net.orcon.kanban.controllers.CardController.java

@PreAuthorize("hasPermission(#boardId, 'BOARD', 'READ,WRITE,ADMIN')")
@RequestMapping(value = "/{cardId}/notifications/{type}", method = RequestMethod.GET, params = { "startDate",
        "endDate" })
public @ResponseBody Collection<CardNotification> getNotifications(@PathVariable String boardId,
        @PathVariable String phaseId, @PathVariable String cardId, @PathVariable String type,
        @RequestParam String startDate, @RequestParam String endDate) throws Exception {

    logger.debug("Attempting to retrieve all unprocessed Notifications of type:'" + type + "' from startDate:'"
            + startDate + "' to endDate:'" + startDate + " for card:'" + cardId + " in phase:'" + phaseId
            + " on board:'" + boardId + "''.");

    final List<CardNotification> notifications = new ArrayList<CardNotification>();

    if (StringUtils.isAlphanumeric(type)) {

        ObjectContentManager ocm = ocmFactory.getOcm();
        try {//w  w  w .  jav  a 2s .  c om
            notifications.addAll(retrieveNotifications(ocm,
                    String.format(URI.CARD_NOTIFICATIONS_URI, boardId, phaseId, cardId, type), startDate,
                    endDate));
            logger.info("Successfully retrieved '" + notifications.size() + "' Notifications of type:'" + type
                    + "'.");
        } catch (Exception e) {
            logger.error("Failed to retrieve '" + notifications.size() + "' Notifications of type:'" + type
                    + "' from startDate:'" + startDate + "' to endDate:'" + startDate + " for card:'" + cardId
                    + " in phase:'" + phaseId + " on board:'" + boardId + "''.");
            throw e;
        } finally {
            ocm.logout();
        }
    }
    return notifications;
}

From source file:nz.net.orcon.kanban.controllers.NotificationController.java

/**
 * Create new JCR node if it does not exist
 * Create an initialise the notification if it does not exist
 * @param notificationType/*from   w w w .  ja v a2  s .co m*/
 * @throws Exception
 */
@RequestMapping(value = "", method = RequestMethod.POST)
public @ResponseBody void createNotificationType(@RequestBody Notification notification) throws Exception {
    LOG.debug("Attempting to create new Notification Type:'" + notification + "'.");

    if (null != notification) {
        final String type = notification.getName();
        if (StringUtils.isAlphanumeric(type)) {
            ObjectContentManager ocm = ocmFactory.getOcm();
            try {
                if (!doesNotificationTypeExist(type, ocm)) {
                    notification.setPath(String.format(URI.NOTIFICATIONS_TYPE_URI, type));
                    ocm.insert(notification);
                    ocm.save();

                    LOG.info("Created new Notification Type:'" + type + "' to JCR Repository.");
                } else {
                    LOG.info("Failed to create new Notification Type:'" + type + "', type already exists.");
                }
            } finally {
                ocm.logout();
            }
        } else {
            LOG.error("Failed to store invalid Notification Type:'" + notification
                    + "' to JCR Repository.  Notification Type was not alphanumeric");
        }
    }
}

From source file:nz.net.orcon.kanban.controllers.NotificationController.java

@RequestMapping(value = "/{type}", method = RequestMethod.GET, params = { "startDate", "endDate" })
public @ResponseBody Collection<CardNotification> getUnProcessedNotifications(@PathVariable String type,
        @RequestParam String startDate, @RequestParam String endDate) throws Exception {
    final List<CardNotification> notifications = new ArrayList<CardNotification>();

    if (StringUtils.isAlphanumeric(type)) {

        ObjectContentManager ocm = ocmFactory.getOcm();
        try {/* w w  w  .  j a va  2  s  .c  o m*/

            final String queryUri = String.format(URI.NOTIFICATIONS_TYPE_URI, type) + "//";

            final List<String> conditions = Arrays.asList(new String[] {
                    String.format("@%s<=xs:dateTime('%s')", "occuredTime", listTools.jcrDateFormat(endDate)),
                    String.format("@%s>=xs:dateTime('%s')", "occuredTime",
                            listTools.jcrDateFormat(startDate)) });

            notifications.addAll(listTools.retrieveObjects(ocm, queryUri, conditions, CardNotification.class));

        } catch (Exception e) {
            LOG.error("Failed to retrieve Unprocessed Notifications of type:'" + type + "' from startDate:'"
                    + startDate + "' to endDate:'" + endDate + "'. Exception:" + e.getMessage());
            throw e;
        } finally {
            ocm.logout();
        }
    }
    return notifications;
}

From source file:org.ahp.commons.validator.ValidatorUtil.java

public static boolean isAlphaNumeric(String pInputString) {
    return StringUtils.isAlphanumeric(pInputString);
}