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:cn.wanghaomiao.seimi.core.SeimiProcessor.java

private Response renderResponse(HttpResponse httpResponse, Request request, HttpContext httpContext) {
    Response seimiResponse = new Response();
    HttpEntity entity = httpResponse.getEntity();
    seimiResponse.setHttpResponse(httpResponse);
    seimiResponse.setReponseEntity(entity);
    seimiResponse.setRealUrl(getRealUrl(httpContext));
    seimiResponse.setUrl(request.getUrl());
    seimiResponse.setRequest(request);//  w w w.j  a  v a2s  .  c o  m
    seimiResponse.setMeta(request.getMeta());

    if (entity != null) {
        Header referer = httpResponse.getFirstHeader("Referer");
        if (referer != null) {
            seimiResponse.setReferer(referer.getValue());
        }
        if (!entity.getContentType().getValue().contains("image")) {
            seimiResponse.setBodyType(BodyType.TEXT);
            try {
                seimiResponse.setData(EntityUtils.toByteArray(entity));
                ContentType contentType = ContentType.get(entity);
                Charset charset = contentType.getCharset();
                if (charset == null) {
                    seimiResponse.setContent(new String(seimiResponse.getData(), "ISO-8859-1"));
                    String docCharset = renderRealCharset(seimiResponse);
                    seimiResponse.setContent(
                            new String(seimiResponse.getContent().getBytes("ISO-8859-1"), docCharset));
                    seimiResponse.setCharset(docCharset);
                } else {
                    seimiResponse.setContent(new String(seimiResponse.getData(), charset));
                    seimiResponse.setCharset(charset.name());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("no content data");
            }
        } else {
            seimiResponse.setBodyType(BodyType.BINARY);
            try {
                seimiResponse.setData(EntityUtils.toByteArray(entity));
                seimiResponse.setContent(StringUtils.substringAfterLast(request.getUrl(), "/"));
            } catch (Exception e) {
                logger.error("no data can be read from httpResponse");
            }
        }
    }
    return seimiResponse;
}

From source file:com.gargoylesoftware.htmlunit.html.XmlSerializer.java

/**
 * Computes the best file to save the response to the given URL.
 * @param url the requested URL/*from ww  w . ja va  2  s.c om*/
 * @param extension the preferred extension
 * @return the file to create
 * @throws IOException if a problem occurs creating the file
 */
private File createFile(final String url, final String extension) throws IOException {
    String name = url.replaceFirst("/$", "");
    name = CREATE_FILE_PATTERN.matcher(name).replaceAll("");
    name = StringUtils.substringBefore(name, "?"); // remove query
    name = StringUtils.substringBefore(name, ";"); // remove additional info
    name = StringUtils.substring(name, 0, 30); // many file systems have a limit at 255, let's limit it
    name = com.gargoylesoftware.htmlunit.util.StringUtils.sanitizeForFileName(name);
    if (!name.endsWith(extension)) {
        name += extension;
    }
    int counter = 0;
    while (true) {
        final String fileName;
        if (counter != 0) {
            fileName = StringUtils.substringBeforeLast(name, ".") + "_" + counter + "."
                    + StringUtils.substringAfterLast(name, ".");
        } else {
            fileName = name;
        }
        outputDir_.mkdirs();
        final File f = new File(outputDir_, fileName);
        if (f.createNewFile()) {
            return f;
        }
        counter++;
    }
}

From source file:com.inkubator.hrm.service.impl.OhsaIncidentDocumentServiceImpl.java

private String getUploadPath(Integer id, UploadedFile documentFile) {
    String extension = StringUtils.substringAfterLast(documentFile.getFileName(), ".");
    String uploadPath = facesIO.getPathUpload() + "ohsaIncidentDocument_" + id + "." + extension;
    return uploadPath;
}

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

protected JsonObject createDirNode(String path) {
    JsonObject node = new JsonObject();
    String title = StringUtils.substringAfterLast(path, "/");
    if (StringUtils.isEmpty(title) == true) {
        if (StringUtils.isEmpty(path) == true) {
            title = "Root";
        } else {/*from   w w w  .  j  av  a 2  s .c om*/
            title = path;
        }
    }
    String id = StringUtils.replace(path, "/", "_");
    node.add("id", id);
    node.add("url", path);

    node.add("text", title);
    node.add("children", new JsonArray());
    JsonObject data = new JsonObject();
    node.add("data", data);
    data.add("url", path);
    return node;
}

From source file:com.gargoylesoftware.htmlunit.util.DebuggingWebConnection.java

/**
 * Computes the best file to save the response to the given URL.
 * @param url the requested URL//  w  w w  . j  a  v  a 2s .  co  m
 * @param extension the preferred extension
 * @return the file to create
 * @throws IOException if a problem occurs creating the file
 */
private File createFile(final URL url, final String extension) throws IOException {
    String name = url.getPath().replaceFirst("/$", "").replaceAll(".*/", "");
    name = StringUtils.substringBefore(name, "?"); // remove query
    name = StringUtils.substringBefore(name, ";"); // remove additional info
    name = StringUtils.substring(name, 0, 30); // avoid exceptions due to too long file names
    name = com.gargoylesoftware.htmlunit.util.StringUtils.sanitizeForFileName(name);
    if (!name.endsWith(extension)) {
        name += extension;
    }
    int counter = 0;
    while (true) {
        final String fileName;
        if (counter != 0) {
            fileName = StringUtils.substringBeforeLast(name, ".") + "_" + counter + "."
                    + StringUtils.substringAfterLast(name, ".");
        } else {
            fileName = name;
        }
        final File f = new File(reportFolder_, fileName);
        if (f.createNewFile()) {
            return f;
        }
        counter++;
    }
}

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

public StreamedContent getMedicalFile() throws IOException {
    FacesContext context = FacesUtil.getFacesContext();
    String id = context.getExternalContext().getRequestParameterMap().get("permitId");

    if (context.getRenderResponse() || id == null) {
        return new DefaultStreamedContent();
    } else {/*ww  w  .j  a va 2s  . co  m*/
        InputStream is = null;
        try {
            MedicalCare medicalCare = medicalCareService.getEntiyByPK(Long.parseLong(id));
            String path = medicalCare.getUploadPath();
            if (StringUtils.isEmpty(path)) {
                path = facesIO.getPathUpload() + "no_image.png";
            }
            is = facesIO.getInputStreamFromURL(path);

            return new DefaultStreamedContent(is, null, StringUtils.substringAfterLast(path, "/"));

        } catch (Exception ex) {
            LOGGER.error(ex, ex);
            return new DefaultStreamedContent();
        }
    }
}

From source file:com.xpn.xwiki.objects.BaseObject.java

@Override
public List<ObjectDiff> getDiff(Object oldEntity, XWikiContext context) {
    ArrayList<ObjectDiff> difflist = new ArrayList<ObjectDiff>();
    BaseObject oldObject = (BaseObject) oldEntity;
    // Iterate over the new properties first, to handle changed and added objects
    for (String propertyName : this.getPropertyList()) {
        BaseProperty newProperty = (BaseProperty) this.getField(propertyName);
        BaseProperty oldProperty = (BaseProperty) oldObject.getField(propertyName);
        BaseClass bclass = getXClass(context);
        PropertyClass pclass = (PropertyClass) ((bclass == null) ? null : bclass.getField(propertyName));
        String propertyType = (pclass == null) ? ""
                : StringUtils.substringAfterLast(pclass.getClassType(), ".");

        if (oldProperty == null) {
            // The property exist in the new object, but not in the old one
            if ((newProperty != null) && (!newProperty.toText().equals(""))) {
                String newPropertyValue = (newProperty.getValue() instanceof String || pclass == null)
                        ? newProperty.toText()
                        : pclass.displayView(propertyName, this, context);
                difflist.add(new ObjectDiff(getXClassReference(), getNumber(), getGuid(),
                        ObjectDiff.ACTION_PROPERTYADDED, propertyName, propertyType, "", newPropertyValue));
            }/*from  w w w .j  av  a  2  s .  co  m*/
        } else if (!oldProperty.toText().equals(((newProperty == null) ? "" : newProperty.toText()))) {
            // The property exists in both objects and is different
            if (pclass != null) {
                // Put the values as they would be displayed in the interface
                String newPropertyValue = (newProperty.getValue() instanceof String || pclass == null)
                        ? newProperty.toText()
                        : pclass.displayView(propertyName, this, context);
                String oldPropertyValue = (oldProperty.getValue() instanceof String || pclass == null)
                        ? oldProperty.toText()
                        : pclass.displayView(propertyName, oldObject, context);
                difflist.add(new ObjectDiff(getXClassReference(), getNumber(), getGuid(),
                        ObjectDiff.ACTION_PROPERTYCHANGED, propertyName, propertyType, oldPropertyValue,
                        newPropertyValue));
            } else {
                // Cannot get property definition, so use the plain value
                difflist.add(new ObjectDiff(getXClassReference(), getNumber(), getGuid(),
                        ObjectDiff.ACTION_PROPERTYCHANGED, propertyName, propertyType, oldProperty.toText(),
                        newProperty.toText()));
            }
        }
    }

    // Iterate over the old properties, in case there are some removed properties
    for (String propertyName : oldObject.getPropertyList()) {
        BaseProperty newProperty = (BaseProperty) this.getField(propertyName);
        BaseProperty oldProperty = (BaseProperty) oldObject.getField(propertyName);
        BaseClass bclass = getXClass(context);
        PropertyClass pclass = (PropertyClass) ((bclass == null) ? null : bclass.getField(propertyName));
        String propertyType = (pclass == null) ? ""
                : StringUtils.substringAfterLast(pclass.getClassType(), ".");

        if (newProperty == null) {
            // The property exists in the old object, but not in the new one
            if ((oldProperty != null) && (!oldProperty.toText().equals(""))) {
                if (pclass != null) {
                    // Put the values as they would be displayed in the interface
                    String oldPropertyValue = (oldProperty.getValue() instanceof String) ? oldProperty.toText()
                            : pclass.displayView(propertyName, oldObject, context);
                    difflist.add(new ObjectDiff(oldObject.getXClassReference(), oldObject.getNumber(),
                            oldObject.getGuid(), ObjectDiff.ACTION_PROPERTYREMOVED, propertyName, propertyType,
                            oldPropertyValue, ""));
                } else {
                    // Cannot get property definition, so use the plain value
                    difflist.add(new ObjectDiff(oldObject.getXClassReference(), oldObject.getNumber(),
                            oldObject.getGuid(), ObjectDiff.ACTION_PROPERTYREMOVED, propertyName, propertyType,
                            oldProperty.toText(), ""));
                }
            }
        }
    }

    return difflist;
}

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

private ServiceLevelAgreement saveAndScheduleSla(ServiceLevelAgreementGroup serviceLevelAgreement,
        FeedMetadata feed) {//from   ww  w. j  a  v a 2 s  .  co  m
    return metadataAccess.commit(() -> {

        if (serviceLevelAgreement != null) {
            ServiceLevelAgreementMetricTransformerHelper transformer = new ServiceLevelAgreementMetricTransformerHelper();
            if (feed != null) {
                transformer.applyFeedNameToCurrentFeedProperties(serviceLevelAgreement,
                        feed.getCategory().getSystemName(), feed.getSystemFeedName());
            }
            ServiceLevelAgreement sla = transformer.getServiceLevelAgreement(serviceLevelAgreement);

            ServiceLevelAgreementBuilder slaBuilder = null;
            com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement.ID existingId = null;
            if (StringUtils.isNotBlank(sla.getId())) {
                existingId = slaProvider.resolve(sla.getId());
            }
            if (existingId != null) {
                slaBuilder = slaProvider.builder(existingId);
            } else {
                slaBuilder = slaProvider.builder();
            }

            slaBuilder.name(sla.getName()).description(sla.getDescription());
            for (com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup group : sla.getGroups()) {
                ObligationGroupBuilder groupBuilder = slaBuilder
                        .obligationGroupBuilder(ObligationGroup.Condition.valueOf(group.getCondition()));
                for (Obligation o : group.getObligations()) {
                    groupBuilder.obligationBuilder().metric(o.getMetrics()).description(o.getDescription())
                            .build();
                }
                groupBuilder.build();
            }
            com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement savedSla = slaBuilder.build();

            List<ServiceLevelAgreementActionConfiguration> actions = transformer
                    .getActionConfigurations(serviceLevelAgreement);

            // now assign the sla checks
            slaProvider.slaCheckBuilder(savedSla.getId()).removeSlaChecks().actionConfigurations(actions)
                    .build();

            //all referencing Feeds
            List<String> systemCategoryAndFeedNames = transformer.getCategoryFeedNames(serviceLevelAgreement);
            Set<Feed> slaFeeds = new HashSet<Feed>();
            Set<Feed.ID> slaFeedIds = new HashSet<Feed.ID>();
            for (String categoryAndFeed : systemCategoryAndFeedNames) {
                //fetch and update the reference to the sla
                String categoryName = StringUtils.trim(StringUtils.substringBefore(categoryAndFeed, "."));
                String feedName = StringUtils.trim(StringUtils.substringAfterLast(categoryAndFeed, "."));
                Feed feedEntity = feedProvider.findBySystemName(categoryName, feedName);
                if (feedEntity != null) {
                    slaFeeds.add(feedEntity);
                    slaFeedIds.add(feedEntity.getId());
                }
            }

            if (feed != null) {
                Feed.ID feedId = feedProvider.resolveFeed(feed.getFeedId());
                if (!slaFeedIds.contains(feedId)) {
                    Feed feedEntity = feedProvider.getFeed(feedId);
                    slaFeeds.add(feedEntity);
                }
            }
            //relate them
            feedSlaProvider.relateFeeds(savedSla, slaFeeds);
            com.thinkbiganalytics.metadata.rest.model.sla.FeedServiceLevelAgreement restModel = ServiceLevelAgreementModelTransform
                    .toModel(savedSla, slaFeeds, true);
            //schedule it
            serviceLevelAgreementScheduler.scheduleServiceLevelAgreement(savedSla);
            return restModel;

        }
        return null;

    });

}

From source file:io.cloudex.cloud.impl.google.GoogleCloudServiceImpl.java

/**
 * Perform initialization before//from  www. j  a v a  2s  .c o m
 * this cloud service is used
 * @throws IOException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public VmMetaData init() throws IOException {

    // can't do anything without an authentication provider
    Validate.notNull(this.authenticationProvider);

    Map<String, Object> attributes = null;
    String fingerprint = null;

    this.getHttpTransport();

    if (this.remote) {
        // if not running on a vm on the cloud environment, then
        // these values need to be set externally
        Validate.notNull(this.zone);
        Validate.notNull(this.projectId);
        Validate.notNull(this.instanceId);
        Validate.notNull(this.scopes);

        Credential credential = (Credential) this.authenticationProvider.authorize();

        this.getCompute(credential);
        this.getStorage(credential);
        this.getBigquery(credential);

    } else {
        this.projectId = GoogleMetaData.getMetaData(PROJECT_ID_PATH);
        Map<String, Object> metaData = GoogleMetaData.getMetaDataAsMap(INSTANCE_ALL_PATH);
        attributes = (Map<String, Object>) metaData.get(ATTRIBUTES);

        // strangely zone looks like this: "projects/315344313954/zones/us-central1-a"
        this.zone = (String) metaData.get(ZONE);
        this.zone = StringUtils.substringAfterLast(this.zone, "/");

        // the name isn't returned!, but the hostname looks like this:
        // "ecarf-evm-1.c.ecarf-1000.internal"
        this.instanceId = (String) metaData.get(HOSTNAME);
        this.instanceId = StringUtils.substringBefore(this.instanceId, ".");

        // get the default service account
        Map<String, Object> serviceAccountConfig = ((Map) ((Map) metaData.get(SERVICE_ACCOUNTS)).get(DEFAULT));
        this.serviceAccount = (String) serviceAccountConfig.get(EMAIL);
        this.scopes = (List) serviceAccountConfig.get(SCOPES);
        // add the datastore scope as well
        this.scopes.add(DATASTORE_SCOPE);

        // no need for this call right now
        //this.authorise();
        this.getCompute();
        this.getStorage();
        this.getBigquery();

        boolean retrying = true;
        int retries = 0;
        Instance instance = null;

        do {
            try {
                // java.net.SocketTimeoutException: connect timed out
                instance = this.getInstance(instanceId, zone);
                retrying = false;

            } catch (IOException e) {
                log.error("Failed to retrieve instance details, retries: " + retries, e);
                retries++;
                if (retries > 3) {
                    throw e;
                }
                ApiUtils.block(this.getApiRecheckDelay());
            }

        } while (retrying);

        fingerprint = instance.getMetadata().getFingerprint();
    }

    log.debug("Successfully initialized Google Cloud Service: " + this);
    return new VmMetaData(attributes, fingerprint);

}

From source file:com.streamsets.datacollector.restapi.PreviewResource.java

@Path("/pipeline/dynamicPreview")
@POST/* w w w.j  a  va 2  s  .c o  m*/
@ApiOperation(value = "Run dynamic pipeline preview", response = PreviewInfoJson.class, authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed({ AuthzRole.CREATOR, AuthzRole.ADMIN, AuthzRole.CREATOR_REMOTE, AuthzRole.ADMIN_REMOTE,
        AuthzRole.MANAGER, AuthzRole.MANAGER_REMOTE })
public Response initiateDynamicPreview(
        @ApiParam(name = "dynamicPreviewRequest", required = true) DynamicPreviewRequestWithOverridesJson dynamicPreviewWithOverridesRequest)
        throws StageException, IOException {
    Utils.checkNotNull(dynamicPreviewWithOverridesRequest, "dynamicPreviewWithOverridesRequest");
    final DynamicPreviewRequestJson dynamicPreviewRequest = dynamicPreviewWithOverridesRequest
            .getDynamicPreviewRequestJson();

    Utils.checkNotNull(dynamicPreviewRequest, "dynamicPreviewRequestJson");

    checkDynamicPreviewPermissions(dynamicPreviewRequest);

    // TODO: fix this hack?
    final String orgId = StringUtils.substringAfterLast(currentUser.getName(), "@");
    final Map<String, Object> params = dynamicPreviewRequest.getParameters();
    params.put(DynamicPreviewConstants.REQUESTING_USER_ID_PARAMETER, currentUser.getName());
    params.put(DynamicPreviewConstants.REQUESTING_USER_ORG_ID_PARAMETER, orgId);

    final String controlHubBaseUrl = RemoteSSOService.getValidURL(
            configuration.get(RemoteSSOService.DPM_BASE_URL_CONFIG, RemoteSSOService.DPM_BASE_URL_DEFAULT));

    // serialize the stage overrides to a String, to be passed to Control Hub (see Javadocs in DynamicPreviewRequestJson
    // for a more complete explanation)
    dynamicPreviewRequest.setStageOutputsToOverrideJsonText(ObjectMapperFactory.get()
            .writeValueAsString(dynamicPreviewWithOverridesRequest.getStageOutputsToOverrideJson()));

    final DynamicPreviewEventJson dynamicPreviewEvent = getDynamicPreviewEvent(controlHubBaseUrl,
            "/dynamic_preview/rest/v2/dynamic_preview/createDynamicPreviewEvent", runtimeInfo.getAppAuthToken(),
            runtimeInfo.getId(), dynamicPreviewRequest);

    String generatedPipelineId = null;
    try {
        generatedPipelineId = handlePreviewEvents("before", dynamicPreviewEvent.getBeforeActionsEventTypeIds(),
                dynamicPreviewEvent.getBeforeActions());
    } catch (IOException e) {
        throw new StageException(PreviewError.PREVIEW_0101, "before", e.getMessage(), e);
    }

    if (generatedPipelineId == null) {
        throw new StageException(PreviewError.PREVIEW_0103);
    }

    final PipelinePreviewEvent previewEvent = MessagingDtoJsonMapper.INSTANCE
            .asPipelinePreviewEventDto(dynamicPreviewEvent.getPreviewEvent());

    // set up after actions
    previewEvent.setAfterActionsFunction(p -> {
        LOG.debug("Running after actions for dynamic preview");
        try {
            handlePreviewEvents("after", dynamicPreviewEvent.getAfterActionsEventTypeIds(),
                    dynamicPreviewEvent.getAfterActions());
        } catch (IOException e) {
            LOG.error("IOException attempting to handle after actions for dynamic preview: {}", e.getMessage(),
                    e);
        }
        return null;
    });

    final RemoteDataCollectorResult previewEventResult = eventHandlerTask.handleLocalEvent(previewEvent,
            EventType.fromValue(dynamicPreviewEvent.getPreviewEventTypeId()));

    String previewerId = null;

    if (previewEventResult.getImmediateResult() == null) {
        throw new StageException(PreviewError.PREVIEW_0102);
    } else {
        previewerId = (String) previewEventResult.getImmediateResult();
    }
    final Previewer previewer = manager.getPreviewer(previewerId);
    final PreviewInfoJson previewInfoJson = new PreviewInfoJson(previewer.getId(), previewer.getStatus(),
            generatedPipelineId);
    return Response.ok().type(MediaType.APPLICATION_JSON).entity(previewInfoJson).build();
}