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:org.ebayopensource.turmeric.eclipse.ui.AbstractSOAResourceWizardPage.java

@Override
protected boolean dialogChanged() {
    if (super.dialogChanged() == false)
        return false;
    if (this.resourceNameText != null) {
        final String resourceName = getResourceName();
        if (StringUtils.isBlank(resourceName)) {
            String resourceLabel = StringUtils.replaceOnce(resourceNameLabel.getText(), "&",
                    SOAProjectConstants.EMPTY_STRING);
            if (resourceLabel.endsWith(SOAProjectConstants.DELIMITER_SEMICOLON))
                resourceLabel = StringUtils.left(resourceLabel, resourceLabel.length() - 1);
            updateStatus(this.resourceNameText, resourceLabel + " must not be empty");
            return false;
        }/*  w w  w  .  j a v a  2  s  .  co  m*/

        /*final InputObject inputObject = new InputObject(resourceName,
              RegExConstants.PROJECT_NAME_EXP,
              ErrorMessage.PROJECT_NAME_ERRORMSG);
                
        try {
           IStatus validationModel = NameValidator.getInstance().validate(
          inputObject);
           if (checkValidationResult(validationModel) == false)
              return false;
        } catch (ValidationInterruptedException e) {
           processException(e);
        }*/
        if (validateName(this.resourceNameText, resourceName, RegExConstants.PROJECT_NAME_EXP,
                ErrorMessage.PROJECT_NAME_ERRORMSG + " The name [" + resourceName
                        + "] is not valid against the pattern \"" + RegExConstants.PROJECT_NAME_EXP
                        + "\"") == false) {
            return false;
        }

    }
    if (resourceVersionText != null) {
        if (StringUtils.isBlank(getResourceVersion())) {
            updateStatus(resourceVersionText, "Version must not be empty");
            return false;
        }
        ServiceVersionValidator serviceVersionValidator = ServiceVersionValidator.getInstance();

        try {
            IStatus validationModel = serviceVersionValidator.validate(getResourceVersion());
            if (checkValidationResult(this.resourceVersionText, validationModel) == false)
                return false;
        } catch (ValidationInterruptedException e) {
            processException(e);
        }

    }
    return true;
}

From source file:org.eclipse.gyrex.admin.ui.cloud.internal.zookeeper.ZooKeeperData.java

public String getLabel() {
    final Stat stat = getStat();

    // print the first few chars if string based
    if ((stat.getDataLength() > 0) && isStringBased()) {
        final String data = StringUtils.left(String.valueOf(getData()), 70);
        if (stat.getEphemeralOwner() != 0)
            return String.format("%s (ephemeral, v%d) [%s]", path.segmentCount() > 0 ? path.lastSegment() : "/",
                    stat.getVersion(), data);
        else//  ww  w  .ja  v  a  2  s .  c om
            return String.format("%s (v%d) [%s]", path.segmentCount() > 0 ? path.lastSegment() : "/",
                    stat.getVersion(), data);
    }

    if (stat.getEphemeralOwner() != 0)
        return String.format("%s (ephemeral, v%d)", path.segmentCount() > 0 ? path.lastSegment() : "/",
                stat.getVersion());
    else if (stat.getDataLength() > 0)
        return String.format("%s (v%d, c%d, %d bytes)", path.segmentCount() > 0 ? path.lastSegment() : "/",
                stat.getVersion(), stat.getCversion(), stat.getDataLength());
    else
        return String.format("%s (v%d, c%d)", path.segmentCount() > 0 ? path.lastSegment() : "/",
                stat.getVersion(), stat.getCversion());
}

From source file:org.eclipse.gyrex.jobs.internal.manager.JobManagerImpl.java

private void setJobResult(final JobImpl job, final Map<String, String> parameter, final IStatus result,
        final long resultTimestamp, final long startTimestamp, final String queueTrigger,
        final long queueTimestamp, final IExclusiveLock lock) throws BackingStoreException {
    if ((null == lock) || !lock.isValid())
        throw new IllegalStateException(String
                .format("Unable to update job result of job %s due to missing or lost job lock!", job.getId()));
    if (null == result)
        throw new IllegalStateException(
                String.format("Unable to update job result of job %s due to missing result!", job.getId()));

    final String internalId = toInternalId(job.getId());
    if (!CloudPreferncesJobStorage.getJobsNode().nodeExists(internalId))
        // don't update if removed
        return;/*from w ww  .j a va 2 s  .  c  o m*/

    // update job node
    final Preferences jobNode = CloudPreferncesJobStorage.getJobsNode().node(internalId);
    jobNode.putLong(CloudPreferncesJobStorage.PROPERTY_LAST_RESULT, resultTimestamp);
    jobNode.put(CloudPreferncesJobStorage.PROPERTY_LAST_RESULT_MESSAGE,
            StringUtils.left(CloudPreferncesJobHistoryStorage.getFormattedMessage(result, 0),
                    CloudPreferncesJobHistoryStorage.MAX_RESULT_MESSAGE_SIZE));
    jobNode.putInt(CloudPreferncesJobStorage.PROPERTY_LAST_RESULT_SEVERITY, result.getSeverity());
    if (!result.matches(IStatus.CANCEL | IStatus.ERROR)) {
        // every run that does not result in ERROR or CANCEL is considered successful
        jobNode.putLong(CloudPreferncesJobStorage.PROPERTY_LAST_SUCCESSFUL_FINISH, resultTimestamp);
        jobNode.putLong(CloudPreferncesJobStorage.PROPERTY_LAST_SUCCESSFUL_START, startTimestamp);
    }
    jobNode.flush();

    // save history
    final IJobHistoryStorage storage = getJobHistoryStore();
    if (storage != null) {
        final JobHistoryEntryStorable storable = new JobHistoryEntryStorable();
        storable.setResult(result);
        storable.setTimestamp(resultTimestamp);
        storable.setParameter(parameter);
        storable.setQueuedTrigger(queueTrigger);
        // only pass cancellation trigger to history if it makes sense
        // (is there a more reliable way to pass the cancel trigger to the history?)
        if ((job.getLastCancelled() > job.getLastQueued()) && (job.getLastQueued() < resultTimestamp)) {
            storable.setCancelledTrigger(job.getLastCancelledTrigger());
        }

        try {
            storage.add(job.getId(), storable);
        } catch (final Exception e) {
            LOG.error("Error persisting job history for job '{}' (context {}). {}", job.getId(),
                    context.getContextPath(), ExceptionUtils.getRootCauseMessage(e), e);
        }
    }
}

From source file:org.eclipse.gyrex.jobs.internal.storage.CloudPreferncesJobHistoryStorage.java

private static IStatus convertStatus(final IStatus status) {
    // FIXME: implement better deserialization of Status (must support MultiStatus and plug-in id, but don't need to support exception)
    // for now we just convert the message to not loose any important information
    return new Status(status.getSeverity(), JobsActivator.SYMBOLIC_NAME,
            StringUtils.left(getFormattedMessage(status, 0), MAX_RESULT_MESSAGE_SIZE));
}

From source file:org.eclipse.jubula.tools.internal.utils.generator.ToolkitInfo.java

/**
 * formats the toolkit type into a shorter version that will
 * use internally//from   www .  j  av  a  2 s . c  o m
 */
private void calculateShortType() {
    String shortType;
    String[] tokens = StringUtils.split(m_type, '.');
    final int tokenLength = tokens.length;
    if (tokenLength > 0) {
        shortType = tokens[tokenLength - 1];
    } else {
        shortType = m_type;
    }
    // Strip off ToolkitPlugin, so that we're left with Abstract, Swt, etc.
    final String needle = "ToolkitPlugin"; //$NON-NLS-1$
    if (shortType.endsWith(needle)) {
        shortType = StringUtils.left(shortType, shortType.indexOf(needle));
    }
    m_shortType = shortType;
}

From source file:org.eclipse.mylyn.reviews.ui.spi.editor.ReviewDetailSection.java

protected void createDependenciesSubSection(final FormToolkit toolkit, final Composite parent, String title,
        List<IChange> changes) {
    if (changes.isEmpty()) {
        return;//from  www  .  ja v  a 2s.  c  o  m
    }

    int style = ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT;

    final Section subSection = toolkit.createSection(parent, style);
    GridDataFactory.fillDefaults().grab(true, false).applyTo(subSection);
    subSection.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE));
    subSection.setText(title);

    Composite composite = toolkit.createComposite(subSection);
    GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 5).applyTo(composite);
    subSection.setClient(composite);

    for (final IChange change : changes) {
        Link link = new Link(composite, SWT.NONE);
        String changeStatus = change.getState() != null
                ? NLS.bind(Messages.ReviewDetailSection_Bracket_X_bracket,
                        String.valueOf(change.getState().getName()))
                : " "; //$NON-NLS-1$
        String ownerName = change.getOwner().getDisplayName();
        link.setText(NLS.bind(Messages.ReviewDetailSection_Link_W_X_Y_by_Z, new String[] {
                StringUtils.left(change.getKey(), 9), change.getSubject(), ownerName, changeStatus }));
        link.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                TasksUiUtil.openTask(getTaskEditorPage().getTaskRepository(), change.getId());
            }
        });
    }
}

From source file:org.eclipse.smarthome.binding.lifx.internal.fields.MACAddress.java

private void formatHex(String original, int length, String separator) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(original.getBytes());
    byte[] buffer = new byte[length];
    String result = "";
    while (bis.read(buffer) > 0) {
        for (byte b : buffer) {
            result += (char) b;
        }/*  w  w  w  . j a va2  s .  c  o m*/
        Arrays.fill(buffer, (byte) 0);
        result += separator;
    }

    hex = StringUtils.left(result, result.length() - 1);

}

From source file:org.ednovo.gooru.domain.service.assessment.AssessmentServiceImpl.java

@Override
public AssessmentQuestion updateQuestionAssest(String gooruQuestionId, String fileNames) throws Exception {
    AssessmentQuestion question = getQuestion(gooruQuestionId);
    final String repositoryPath = question.getOrganization().getNfsStorageArea().getInternalPath();
    final String mediaFolderPath = repositoryPath + "/" + Constants.UPLOADED_MEDIA_FOLDER;
    String[] assetKeyArr = fileNames.split("\\s*,\\s*");
    for (int i = 0; i < assetKeyArr.length; i++) {
        String resourceImageFile = mediaFolderPath + "/" + assetKeyArr[i];
        File mediaImage = new File(resourceImageFile);
        if (!mediaImage.isFile()) {
            throw new BadRequestException("file not found");
        }/*from   www .  j av a2  s .  com*/
        String assetKey = StringUtils.left(assetKeyArr[i], assetKeyArr[i].indexOf("_"));
        String fileName = assetKeyArr[i].split("_")[1];
        byte[] fileContent = FileUtils.readFileToByteArray(mediaImage);
        if (fileContent.length > 0) {
            AssessmentQuestionAssetAssoc questionAsset = null;
            if (assetKey != null && assetKey.length() > 0) {
                questionAsset = getQuestionAsset(assetKey, gooruQuestionId);
            }
            Asset asset = null;
            if (questionAsset == null) {
                asset = new Asset();
                asset.setHasUniqueName(true);
                questionAsset = new AssessmentQuestionAssetAssoc();
                questionAsset.setQuestion(question);
                questionAsset.setAsset(asset);
                questionAsset.setAssetKey(assetKey);
            } else {
                asset = questionAsset.getAsset();
            }
            asset.setFileData(fileContent);
            asset.setName(fileName);
            question.setThumbnail(fileName);
            this.getBaseRepository().save(question);
            Set<AssessmentQuestionAssetAssoc> assets = new HashSet<AssessmentQuestionAssetAssoc>();
            assets.add(uploadQuestionAsset(gooruQuestionId, questionAsset, true));
            question.setAssets(assets);
            mediaImage.delete();
        }
    }
    indexHandler.setReIndexRequest(question.getGooruOid(), IndexProcessor.INDEX, RESOURCE, null, false, false);
    return question;
}

From source file:org.ednovo.gooru.domain.service.collection.QuestionServiceImpl.java

public AssessmentQuestion updateQuestionAssest(String questionId, String fileNames) throws Exception {
    AssessmentQuestion question = getQuestion(questionId);
    final String repositoryPath = question.getOrganization().getNfsStorageArea().getInternalPath();
    final String mediaFolderPath = repositoryPath + "/" + Constants.UPLOADED_MEDIA_FOLDER;
    String[] assetKeyArr = fileNames.split("\\s*,\\s*");
    for (int i = 0; i < assetKeyArr.length; i++) {
        String resourceImageFile = mediaFolderPath + "/" + assetKeyArr[i];
        File mediaImage = new File(resourceImageFile);
        if (!mediaImage.isFile()) {
            throw new BadRequestException(ServerValidationUtils.generateMessage(GL0056, FILE));
        }/*from  w  w w  .  java  2s  .  c  o  m*/
        String assetKey = StringUtils.left(assetKeyArr[i], assetKeyArr[i].indexOf("_"));
        String fileName = assetKeyArr[i].split("_")[1];
        byte[] fileContent = FileUtils.readFileToByteArray(mediaImage);
        if (fileContent.length > 0) {
            AssessmentQuestionAssetAssoc questionAsset = null;
            if (assetKey != null && assetKey.length() > 0) {
                questionAsset = getQuestionAsset(assetKey, questionId);
            }
            Asset asset = null;
            if (questionAsset == null) {
                asset = new Asset();
                asset.setHasUniqueName(true);
                questionAsset = new AssessmentQuestionAssetAssoc();
                questionAsset.setQuestion(question);
                questionAsset.setAsset(asset);
                questionAsset.setAssetKey(assetKey);
            } else {
                asset = questionAsset.getAsset();
            }
            asset.setFileData(fileContent);
            asset.setName(fileName);
            question.setThumbnail(fileName);
            this.getBaseRepository().save(question);
            Set<AssessmentQuestionAssetAssoc> assets = new HashSet<AssessmentQuestionAssetAssoc>();
            assets.add(uploadQuestionAsset(questionId, questionAsset, true));
            question.setAssets(assets);
            mediaImage.delete();
        }
    }
    return question;
}

From source file:org.jahia.admin.sites.ManageSites.java

/**
 * Process Add new site form//from   w  ww  .  j  a  v a 2 s  . com
 *
 * @param request  Servlet request.
 * @param response Servlet response.
 * @param session  HttpSession object.
 */
private void processAdd(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException, ServletException {
    logger.debug("started");

    boolean processError = true;

    // get form values...
    String siteTitle = StringUtils.left(StringUtils.defaultString(request.getParameter("siteTitle")).trim(),
            100);
    String siteServerName = StringUtils
            .left(StringUtils.defaultString(request.getParameter("siteServerName")).trim(), 200);
    String siteKey = StringUtils.left(StringUtils.defaultString(request.getParameter("siteKey")).trim(), 50);
    String siteDescr = StringUtils.left(StringUtils.defaultString(request.getParameter("siteDescr")).trim(),
            250);
    String siteAdmin = StringUtils.defaultString(request.getParameter("siteAdmin")).trim();
    Boolean defaultSite = Boolean.valueOf(request.getParameter("defaultSite") != null);

    request.getSession().setAttribute("siteAdminOption", siteAdmin);
    session.setAttribute("siteAdminOption", siteAdmin);
    String warningMsg = "";
    session.setAttribute(CLASS_NAME + "defaultSite", defaultSite);

    // create jahia site object if checks are in green light...
    try {
        // check validity...
        if (siteTitle != null && (siteTitle.length() > 0) && siteServerName != null
                && (siteServerName.length() > 0) && siteKey != null && (siteKey.length() > 0)) {
            if (!isSiteKeyValid(siteKey)) {
                warningMsg = getMessage("org.jahia.admin.warningMsg.onlyLettersDigitsUnderscore.label");
            } else if (siteKey.equals("site")) {
                warningMsg = getMessage("org.jahia.admin.warningMsg.chooseAnotherSiteKey.label");
            } else if (!isServerNameValid(siteServerName)) {
                warningMsg = getMessage("org.jahia.admin.warningMsg.invalidServerName.label");
            } else if (siteServerName.equals("default")) {
                warningMsg = getMessage("org.jahia.admin.warningMsg.chooseAnotherServerName.label");
            } else if (!Url.isLocalhost(siteServerName) && sMgr.getSite(siteServerName) != null) {
                warningMsg = getMessage("org.jahia.admin.warningMsg.chooseAnotherServerName.label");
            } else if (sMgr.getSiteByKey(siteKey) != null) {
                warningMsg = getMessage("org.jahia.admin.warningMsg.chooseAnotherSiteKey.label");
            } else {
                processError = false;
            }
        } else {
            warningMsg = getMessage("org.jahia.admin.warningMsg.completeRequestInfo.label");
        }

        if (!processError) {
            // save new jahia site...
            JahiaSite site = new JahiaSite(-1, siteTitle, siteServerName, siteKey,
                    // is active
                    // default page (homepage id)... subject to update in terminateAdd().
                    siteDescr, null, null);
            //                site.setTemplatesAutoDeployMode(true);
            //                site.setWebAppsAutoDeployMode(true);

            // set in session...
            session.setAttribute(CLASS_NAME + "newJahiaSite", site);

            // all is okay, go to add admin or use existent admin...
            if (siteAdmin.trim().equals("0")) {
                displayCreateAdmin(request, response, session);
            } else if (siteAdmin.trim().equals("1")) {
                displaySelectExistantAdmin(request, response, session);
            } else {
                displayTemplateSetChoice(request, response, session);
            }

            site = null;
        } else {
            JahiaSite site = new JahiaSite(-1, siteTitle, siteServerName, siteKey, siteDescr, null, null);

            session.setAttribute(CLASS_NAME + "newJahiaSite", site);
            request.setAttribute("newJahiaSite", site);
            request.setAttribute("warningMsg", warningMsg);
            displayAdd(request, response, session);
        }
    } catch (JahiaException ex) {
        warningMsg = getMessage("label.error.processingRequestError");
        request.setAttribute("warningMsg", warningMsg);
        displayAdd(request, response, session);
    } finally {
        siteTitle = null;
        siteServerName = null;
        siteKey = null;
        siteDescr = null;
        siteAdmin = null;
        defaultSite = null;
        warningMsg = null;
        request.getSession().setAttribute("lastPage", "processadd");
    }
}