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

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

Introduction

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

Prototype

public static String substringAfterLast(final String str, final String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:info.magnolia.ui.framework.command.ImportZipCommand.java

protected void handleFileEntry(ZipFile zip, ZipArchiveEntry entry) throws IOException, RepositoryException {
    String fileName = entry.getName();
    if (StringUtils.contains(fileName, "/")) {
        fileName = StringUtils.substringAfterLast(fileName, "/");
    }/*from  w  w w  .  j  a va  2 s  .c o  m*/

    String extension = StringUtils.substringAfterLast(fileName, ".");
    InputStream stream = zip.getInputStream(entry);
    FileOutputStream os = null;
    try {
        UploadReceiver receiver = createReceiver();

        String folderPath = extractEntryPath(entry);
        if (folderPath.startsWith("/")) {
            folderPath = folderPath.substring(1);
        }
        Node folder = getJCRNode(context);
        if (StringUtils.isNotBlank(folderPath)) {
            if (folder.hasNode(folderPath)) {
                folder = folder.getNode(folderPath);
            } else {
                folder = NodeUtil.createPath(folder, folderPath, NodeTypes.Folder.NAME, true);
            }
        }
        receiver.setFieldType(UploadField.FieldType.BYTE_ARRAY);
        receiver.receiveUpload(fileName,
                StringUtils.defaultIfEmpty(MIMEMapping.getMIMEType(extension), DEFAULT_MIME_TYPE));
        receiver.setValue(IOUtils.toByteArray(stream));

        doHandleEntryFromReceiver(folder, receiver);
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(os);
    }
}

From source file:de.vandermeer.skb.datatool.commons.DataUtilities.java

/**
 * Loads an data for an SKB link./*from   ww  w.j a va2s . c om*/
 * @param skbLink the link to load an data for
 * @param loadedTypes loaded types as lookup for links
 * @return an object if successfully loaded, null otherwise
 * @throws IllegalArgumentException if any of the required arguments or map entries are not set or empty
 * @throws URISyntaxException if creating a URI for an SKB link failed
 */
public static Object loadLink(Object skbLink, LoadedTypeMap loadedTypes) throws URISyntaxException {
    if (skbLink == null) {
        throw new IllegalArgumentException("skb link null");
    }
    if (loadedTypes == null) {
        throw new IllegalArgumentException("trying to load a link, but no loaded types given");
    }

    URI uri = new URI(skbLink.toString());
    if (!"skb".equals(uri.getScheme())) {
        throw new IllegalArgumentException("unknown scheme in link <" + skbLink + ">");
    }

    String uriReq = uri.getScheme() + "://" + uri.getAuthority();
    DataEntryType type = null;
    for (DataEntryType det : loadedTypes.keySet()) {
        if (uriReq.equals(det.getLinkUri())) {
            type = det;
            break;
        }
    }
    if (type == null) {
        throw new IllegalArgumentException(
                "no data entry type for link <" + uri.getScheme() + "://" + uri.getAuthority() + ">");
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) loadedTypes.getTypeMap(type);
    if (map == null) {
        throw new IllegalArgumentException("no entry for type <" + type.getType() + "> in link map");
    }

    String key = StringUtils.substringAfterLast(uri.getPath(), "/");
    Object ret = map.get(key);
    if (ret == null) {
        throw new IllegalArgumentException(
                "no entry for <" + uri.getAuthority() + "> key <" + key + "> in link map");
    }
    return ret;
}

From source file:com.netflix.spinnaker.clouddriver.ecs.provider.agent.ServiceCachingAgent.java

@Override
protected Map<String, Collection<CacheData>> generateFreshData(Collection<Service> services) {
    Collection<CacheData> dataPoints = new LinkedList<>();
    Map<String, CacheData> clusterDataPoints = new HashMap<>();

    for (Service service : services) {
        Map<String, Object> attributes = convertServiceToAttributes(accountName, region, service);

        String key = Keys.getServiceKey(accountName, region, service.getServiceName());
        dataPoints.add(new DefaultCacheData(key, attributes, Collections.emptyMap()));

        Map<String, Object> clusterAttributes = EcsClusterCachingAgent
                .convertClusterArnToAttributes(accountName, region, service.getClusterArn());
        String clusterName = StringUtils.substringAfterLast(service.getClusterArn(), "/");
        key = Keys.getClusterKey(accountName, region, clusterName);
        clusterDataPoints.put(key, new DefaultCacheData(key, clusterAttributes, Collections.emptyMap()));
    }/*from   w  w  w  .j a  v  a 2  s  .co  m*/

    log.info("Caching " + dataPoints.size() + " services in " + getAgentType());
    Map<String, Collection<CacheData>> dataMap = new HashMap<>();
    dataMap.put(SERVICES.toString(), dataPoints);

    log.info("Caching " + clusterDataPoints.size() + " ECS clusters in " + getAgentType());
    dataMap.put(ECS_CLUSTERS.toString(), clusterDataPoints.values());

    return dataMap;
}

From source file:info.pancancer.arch3.reporting.SlackRenderer.java

public FormattedMessage convertToResult(String message) {
    String[] words = message.split(" ");

    String firstWord = words[0];/*w ww. j  a  v  a2  s  .  c o m*/
    Commands firstCommand;
    try {
        firstCommand = Commands.valueOf(firstWord);
    } catch (IllegalArgumentException ex) {
        StringBuilder builder = new StringBuilder();
        builder.append("Available commands are:\n");
        for (Map.Entry<String, String> entry : reportAPI.getCommands().entrySet()) {
            builder.append("`").append(entry.getKey()).append("` ");
            builder.append(entry.getValue()).append("\n");
        }
        return new FormattedMessage(builder.toString(), null);
    }

    Map<String, AbstractInstanceListing.InstanceDescriptor> awsInstances;
    Map<String, AbstractInstanceListing.InstanceDescriptor> osInstances;
    Map<String, AbstractInstanceListing.InstanceDescriptor> azureInstances;
    StringBuilder builder = new StringBuilder();
    SlackAttachment attach;
    Map<String, Map<String, String>> jobInfo;

    switch (firstCommand) {

    case STATUS:

        builder.append("*Active VM counts via youxia*:\n");
        awsInstances = reportAPI.getYouxiaInstances(CloudTypes.AWS);
        osInstances = reportAPI.getYouxiaInstances(CloudTypes.OPENSTACK);
        azureInstances = reportAPI.getYouxiaInstances(CloudTypes.AZURE);
        builder.append(awsInstances.size()).append(" instances managed on AWS \n");
        builder.append(osInstances.size()).append(" instances managed on OpenStack \n");
        builder.append(azureInstances.size()).append(" instances managed on Azure \n");

        builder.append("*Historical VM counts*:\n");
        for (Entry<ProvisionState, Long> entry : reportAPI.getVMStateCounts().entrySet()) {
            builder.append(entry.getKey().toString()).append(": ").append(entry.getValue()).append("\n");
        }
        builder.append("*Historical Job counts*:\n");
        for (Entry<JobState, Integer> entry : reportAPI.getJobStateCounts().entrySet()) {
            builder.append(entry.getKey().toString()).append(": ").append(entry.getValue()).append("\n");
        }

        builder.append("\n");
        // determine the intersection of live vms with failed jobs on them
        Map<String, Map<String, String>> vmInfo = reportAPI.getVMInfo(ProvisionState.FAILED);
        if (vmInfo.isEmpty()) {
            builder.append("There are no failed jobs on VMs that require attention\n");
        } else {
            builder.append("*There are failed jobs on VMs that require attention:*\n");
            renderMapOfMaps(vmInfo, builder);
        }

        return new FormattedMessage(builder.toString(), null);

    case YOUXIA:
        awsInstances = reportAPI.getYouxiaInstances(CloudTypes.AWS);
        osInstances = reportAPI.getYouxiaInstances(CloudTypes.OPENSTACK);
        azureInstances = reportAPI.getYouxiaInstances(CloudTypes.AZURE);

        if (awsInstances.size() > 0) {
            renderInstances("AWS", builder, awsInstances);
        }
        if (awsInstances.size() > 0) {
            renderInstances("OpenStack", builder, osInstances);
        }
        if (awsInstances.size() > 0) {
            renderInstances("Azure", builder, azureInstances);
        }

        attach = new SlackAttachment("Live cloud instance info described on " + new Date(), "Live instances",
                builder.toString(), null);
        return new FormattedMessage(null, attach);

    case INFO:
        for (Entry<String, String> entry : reportAPI.getEnvironmentMap().entrySet()) {
            builder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
        }
        return new FormattedMessage(builder.toString(), null);

    case PROVISIONED:
        jobInfo = reportAPI.getVMInfo();
        renderMapOfMaps(jobInfo, builder);
        attach = new SlackAttachment("VM info from DB at " + new Date(), "VMs from DB", builder.toString(),
                null);
        return new FormattedMessage(null, attach);

    case JOBS:
        jobInfo = reportAPI.getJobInfo();
        renderMapOfMaps(jobInfo, builder);
        attach = new SlackAttachment("Job info from DB at " + new Date(), "Jobs from DB", builder.toString(),
                null);
        return new FormattedMessage(null, attach);

    case GATHER:
        Map<String, Status> cache = reportAPI.getLastStatus();
        for (Map.Entry<String, Status> entry : cache.entrySet()) {
            builder.append("*").append(entry.getKey()).append(" reports*:\n");
            String stdout = "`" + StringUtils.substringAfterLast(entry.getValue().getStdout(), "\n") + "`";
            builder.append(stdout).append("\n");
        }
        attach = new SlackAttachment("Messages gathered from queues at " + new Date(), "Messages gathered",
                builder.toString(), null);
        return new FormattedMessage(null, attach);

    default:
        /** do nothing, not a valid command */
    }
    throw new RuntimeException("should not get here in the SlackRenderer");
}

From source file:com.example.office.ui.mail.MailItemFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case MailItemActivity.CAMERA_REQUEST_CODE:
        if (resultCode == Activity.RESULT_OK) {
            try {
                String currentPhotoPath = ((MailItemActivity) getActivity()).getCurrentPhotoPath();
                Bitmap bmp = BitmapFactory.decodeFile(currentPhotoPath);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp.compress(CompressFormat.JPEG, 100, stream);

                MailItem mail = (MailItem) getActivity().getIntent().getExtras()
                        .get(getString(R.string.intent_mail_key));
                Utility.showToastNotification("Starting file uploading");
                mId = mail.getId();/*from   w w w  .j  a v a  2s.c  o  m*/
                mImageBytes = stream.toByteArray();
                mFilename = StringUtils.substringAfterLast(currentPhotoPath, "/");
                getMessageAndAttachData();
            } catch (Exception e) {
                Utility.showToastNotification("Error during getting image from camera");
            }

        }
        break;

    case MailItemActivity.SELECT_PHOTO:
        if (resultCode == Activity.RESULT_OK) {
            try {
                Uri selectedImage = data.getData();
                InputStream imageStream = getActivity().getContentResolver().openInputStream(selectedImage);
                MailItem mail = (MailItem) getActivity().getIntent().getExtras()
                        .get(getString(R.string.intent_mail_key));
                Utility.showToastNotification("Starting file uploading");
                mId = mail.getId();
                mImageBytes = IOUtils.toByteArray(imageStream);
                mFilename = selectedImage.getLastPathSegment();
                getMessageAndAttachData();
            } catch (Throwable t) {
                Utility.showToastNotification("Error during getting image from file");
            }
        }
        break;

    default:
        super.onActivityResult(requestCode, resultCode, data);
    }

}

From source file:com.inkubator.hrm.web.ImageBioDataStreamerController.java

public StreamedContent getIjazahFile() throws IOException {

    FacesContext context = FacesUtil.getFacesContext();
    String bioId = context.getExternalContext().getRequestParameterMap().get("id");
    String url;/*from   www  .  ja  v  a 2s  .  c o  m*/
    String filename;
    if (context.getRenderResponse() || bioId == null) {
        return new DefaultStreamedContent();
    } else {
        InputStream is = null;
        try {
            url = educationHistoryService.getEntiyByPK(Long.parseLong(bioId)).getPathFoto();
            is = facesIO.getInputStreamFromURL(url);
        } catch (Exception ex) {
            LOGGER.error(ex, ex);
            return new DefaultStreamedContent();
        }
        return new DefaultStreamedContent(is, null, StringUtils.substringAfterLast(url, "/"));

    }

}

From source file:com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementModelTransform.java

public static com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement toModel(
        ServiceLevelAgreement domain, boolean deep) {

    com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement sla = new com.thinkbiganalytics.metadata.rest.model.sla.ServiceLevelAgreement(
            domain.getId().toString(), domain.getName(), domain.getDescription());
    if (domain.getSlaChecks() != null) {
        List<ServiceLevelAgreementCheck> checks = new ArrayList<>();
        sla.setSlaChecks(checks);/*from   w  ww.  ja v  a  2s  . com*/
        for (com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementCheck check : domain.getSlaChecks()) {
            ServiceLevelAgreementCheck restModel = new ServiceLevelAgreementCheck();
            restModel.setCronSchedule(check.getCronSchedule());
            if (deep) {
                try {
                    restModel.setActionConfigurations(check.getActionConfigurations());
                } catch (Exception e) {
                    if (ExceptionUtils.getRootCause(e) instanceof ClassNotFoundException) {
                        String msg = ExceptionUtils.getRootCauseMessage(e);
                        //get just the simpleClassName stripping the package info
                        msg = StringUtils.substringAfterLast(msg, ".");
                        sla.addSlaCheckError("Unable to find the SLA Action Configurations of type: " + msg
                                + ". Check with an administrator to ensure the correct plugin is installed with this SLA configuration. ");
                    } else {
                        throw new RuntimeException(e);
                    }
                }
            }
            checks.add(restModel);
        }
    }

    if (deep) {
        if (domain.getObligationGroups().size() == 1
                && domain.getObligationGroups().get(0).getCondition() == ObligationGroup.Condition.REQUIRED) {
            for (Obligation domainOb : domain.getObligations()) {
                com.thinkbiganalytics.metadata.rest.model.sla.Obligation ob = toModel(domainOb, true);
                sla.addObligation(ob);
            }
        } else {
            for (ObligationGroup domainGroup : domain.getObligationGroups()) {
                com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup group = new com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup(
                        domainGroup.getCondition().toString());
                for (Obligation domainOb : domainGroup.getObligations()) {
                    com.thinkbiganalytics.metadata.rest.model.sla.Obligation ob = toModel(domainOb, true);
                    group.addObligation(ob);
                }

                sla.addGroup(group);
            }
        }
    }

    return sla;
}

From source file:de.micromata.genome.gwiki.controls.GWikiUploadAttachmentActionBean.java

public Object onUploadImage() {
    try {//from w w  w  .j a  v  a 2 s  .  c  o  m

        if (wikiContext.getWikiWeb().getAuthorization().needAuthorization(wikiContext) == true) {
            if (StringUtils.isBlank(userName) == true || StringUtils.isBlank(passWord)) {
                return sendResponse(2, wikiContext.getTranslated("gwiki.edit.EditPage.attach.message.nologin"));
            }
            boolean loggedIn = wikiContext.getWikiWeb().getAuthorization().login(wikiContext, userName,
                    passWord);
            if (loggedIn == false) {
                return sendResponse(1,
                        wikiContext.getTranslated("gwiki.edit.EditPage.attach.message.invaliduser"));
            }
        }
        try {
            if (wikiContext.getWikiWeb().getAuthorization().initThread(wikiContext) == false) {
                return sendResponse(2, wikiContext.getTranslated("gwiki.edit.EditPage.attach.message.nologin"));
            }
            if (StringUtils.isEmpty(pageId) == true) {
                pageId = fileName;
            }
            if (StringUtils.isEmpty(pageId) == true) {
                return sendResponse(3,
                        wikiContext.getTranslated("gwiki.edit.EditPage.attach.message.nofilename"));
            }
            if (StringUtils.isEmpty(encData) == true) {
                return sendResponse(4, wikiContext.getTranslated("gwiki.edit.EditPage.attach.message.empty"));
            }
            String base64data = extractImageData(encData);
            byte[] data = Base64.decodeBase64(base64data.getBytes());
            if (StringUtils.isNotEmpty(parentPageId) == true) {
                String pp = GWikiContext.getParentDirPathFromPageId(parentPageId);
                pageId = pp + pageId;
            }
            //        if (storeTmpFile == true) {
            //          FileSystem fs = wikiContext.getWikiWeb().getStorage().getFileSystem();
            //          FsDirectoryObject tmpDir = fs.createTempDir("appletupload", 1000 * 60 * 30);
            //          String nf = FileSystemUtils.mergeDirNames(tmpDir.getName(), pageId);
            //
            //          FileSystem fswrite = fs.getFsForWrite(nf);
            //          String pdirs = FileNameUtils.getParentDir(nf);
            //          fswrite.mkdirs(pdirs);
            //          fswrite.writeBinaryFile(nf, data, true);
            //          
            //          return sendResponse(toMap("rc", "0", "tmpFileName", nf));
            //        } else {
            if (wikiContext.getWikiWeb().findElementInfo(pageId) != null) {

                JsonObject res = new JsonObject();
                res.set("rc", 5);
                res.set("rm", wikiContext.getTranslated("gwiki.edit.EditPage.attach.message.fileexists"));

                String baseName = pageId;
                String suffix = "";
                int idx = baseName.lastIndexOf('.');
                if (idx != -1) {
                    baseName = baseName.substring(0, idx);
                    suffix = pageId.substring(idx);
                }
                for (int i = 1; i < 10; ++i) {
                    String npageId = baseName + i + suffix;
                    if (wikiContext.getWikiWeb().findElementInfo(npageId) == null) {
                        String fnfn = npageId;
                        if (StringUtils.contains(fnfn, '/') == true) {
                            fnfn = StringUtils.substringAfterLast(npageId, "/");
                        }
                        res.set("alternativeFileName", fnfn);
                        break;
                    }
                }

                return sendResponse(res);
            }
            JsonObject res = new JsonObject();
            res.set("rc", 0);
            JsonObject item = new JsonObject();
            res.set("item", item);
            if (StringUtils.isBlank(title) == true) {
                title = fileName;
            }
            String metaTemplateId = "admin/templates/FileWikiPageMetaTemplate";
            GWikiElement el = GWikiWebUtils.createNewElement(wikiContext, pageId, metaTemplateId, title);
            el.getElementInfo().getProps().setStringValue(GWikiPropKeys.PARENTPAGE, parentPageId);
            GWikiArtefakt<?> art = el.getMainPart();
            GWikiBinaryAttachmentArtefakt att = (GWikiBinaryAttachmentArtefakt) art;
            att.setStorageData(data);
            if (data != null) {
                el.getElementInfo().getProps().setIntValue(GWikiPropKeys.SIZE, data.length);
            }

            wikiContext.getWikiWeb().saveElement(wikiContext, el, false);
            item.set("url", el.getElementInfo().getId());
            item.set("title", el.getElementInfo().getTitle());
            return sendResponse(res);

            //        }
        } finally {
            wikiContext.getWikiWeb().getAuthorization().clearThread(wikiContext);
        }
    } catch (Exception ex) {
        GWikiLog.warn("Failure to upload attachment: " + ex.getMessage(), ex);
        sendResponse(10, translate("gwiki.edit.EditPage.attach.message.error", ex.getMessage()));
    }
    return noForward();
}

From source file:de.micromata.genome.gwiki.pagelifecycle_1_0.wizard.TimingStepWizardAction.java

public Object onRenderHeader() {
    wikiContext.getWikiWeb().getDaoContext().getI18nProvider().addTranslationElement(wikiContext,
            "/edit/pagelifecycle/i18n/PlcI18N");
    GWikiElement actionPage = wikiContext.getCurrentElement();
    GWikiElementInfo info = actionPage.getElementInfo();
    String tabTitle = info.getProps().getStringValue(GWikiPropKeys.TITLE);

    if (tabTitle.startsWith("I{") == true) {
        tabTitle = wikiContext.getTranslatedProp(tabTitle);
    }//from w w w.  j ava2  s  . co  m
    String divAnchor = StringUtils.substringAfterLast(info.getId(), "/");
    wikiContext.append("<li><a href='#").append(divAnchor).append("'>").append(tabTitle).append("</a></li>");
    return noForward();
}

From source file:io.mangoo.build.Watcher.java

public void handleNewOrModifiedFile(Path path) {
    String absolutePath = path.toFile().getAbsolutePath();
    if (isPreprocess(absolutePath)) {
        MinificationUtils.preprocess(absolutePath);
        String[] tempPath = absolutePath.split("files");
        MinificationUtils.minify(tempPath[0] + "files/assets/stylesheet/"
                + StringUtils.substringAfterLast(absolutePath, "/")
                        .replace(Suffix.SASS.toString(), Suffix.CSS.toString())
                        .replace(Suffix.LESS.toString(), Suffix.CSS.toString()));
    }/*from w w  w.  java  2  s.  co m*/

    if (isAsset(absolutePath)) {
        MinificationUtils.minify(absolutePath);
    }

    RuleMatch match = matchRule(includes, excludes, absolutePath);
    if (match.proceed) {
        this.trigger.trigger();
    }
}