List of usage examples for org.apache.commons.lang3 StringUtils left
public static String left(final String str, final int len)
Gets the leftmost len characters of a String.
If len characters are not available, or the String is null , the String will be returned without an exception.
From source file:org.dbgl.util.FileUtils.java
private static ShortFile createShortFile(File file, Set<ShortFile> curDir) { String filename = file.getName().toUpperCase(); boolean createShort = false; if (StringUtils.contains(filename, ' ')) { filename = StringUtils.remove(filename, ' '); createShort = true;/*from w w w . ja v a 2s .com*/ } int len = 0; int idx = filename.indexOf('.'); if (idx != -1) { if (filename.length() - idx - 1 > 3) { filename = StringUtils.stripStart(filename, "."); createShort = true; } idx = filename.indexOf('.'); len = (idx != -1) ? idx : filename.length(); } else { len = filename.length(); } createShort |= len > 8; ShortFile shortFile = null; if (!createShort) { shortFile = new ShortFile(file, StringUtils.removeEnd(filename, ".")); } else { int i = 1; do { String nr = String.valueOf(i++); StringBuffer sb = new StringBuffer(StringUtils.left(filename, Math.min(8 - nr.length() - 1, len))); sb.append('~').append(nr); idx = filename.lastIndexOf('.'); if (idx != -1) sb.append(StringUtils.left(filename.substring(idx), 4)); shortFile = new ShortFile(file, StringUtils.removeEnd(sb.toString(), ".")); } while (shortFile.isContainedIn(curDir)); } return shortFile; }
From source file:org.efaps.esjp.admin.util.SysConfigUtil.java
/** * Validate the used SytemConfigurations. * * @param _parameter Parameter as passed by the eFasp API * @throws EFapsException on error//from w ww . ja v a 2s. c o m */ public void validateSysConf(final Parameter _parameter) throws EFapsException { if (checkAccess()) { final QueryBuilder queryBldr = new QueryBuilder(CIAdminCommon.SystemConfigurationAttribute); queryBldr.addType(CIAdminCommon.SystemConfigurationLink); queryBldr.addOrderByAttributeAsc(CIAdminCommon.SystemConfigurationAbstract.Key); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selUUID = SelectBuilder.get() .linkto(CIAdminCommon.SystemConfigurationAbstract.AbstractLink) .attribute(CIAdminCommon.SystemConfiguration.UUID); final SelectBuilder selName = SelectBuilder.get() .linkto(CIAdminCommon.SystemConfigurationAbstract.AbstractLink) .attribute(CIAdminCommon.SystemConfiguration.Name); multi.addSelect(selUUID, selName); multi.addAttribute(CIAdminCommon.SystemConfigurationAbstract.Key); multi.setEnforceSorted(true); multi.execute(); while (multi.next()) { final String uuid = multi.getSelect(selUUID); String key = multi.getAttribute(CIAdminCommon.SystemConfigurationAbstract.Key); final boolean isLink = multi.getCurrentInstance().getType() .isCIType(CIAdminCommon.SystemConfigurationLink); ISysConfAttribute attr = isLink ? SysConfResourceConfig.getResourceConfig().getLink(uuid, key) : SysConfResourceConfig.getResourceConfig().getAttribute(uuid, key); if (attr == null && key.matches(".*\\d\\d$")) { key = StringUtils.left(key, key.length() - 2); attr = isLink ? SysConfResourceConfig.getResourceConfig().getLink(uuid, key) : SysConfResourceConfig.getResourceConfig().getAttribute(uuid, key); } if (attr == null) { LOG.warn("Did not find Key {} defined in {}", key, multi.getSelect(selName)); } else { LOG.debug("Found Key {}", key); } } } }
From source file:org.efaps.ui.wicket.behaviors.dojo.AutoCompleteBehavior.java
/** * @param _target target/*from w ww . j a v a 2 s.c om*/ * @param _val value */ protected void respond(final ACAjaxRequestTarget _target, final String _val) { final AutoCompleteField field = (AutoCompleteField) getComponent(); final Iterator<Map<String, String>> choices = field.getChoices(_val); try { final JSONArray jsonArray = new JSONArray(); int i = 0; while (choices.hasNext() && (i < this.settings.getMaxResult() || this.settings.getMaxResult() == -1)) { final Map<String, String> map = choices.next(); final String key = map.get(EFapsKey.AUTOCOMPLETE_KEY.getKey()) != null ? map.get(EFapsKey.AUTOCOMPLETE_KEY.getKey()) : map.get(EFapsKey.AUTOCOMPLETE_VALUE.getKey()); final String choice = map.get(EFapsKey.AUTOCOMPLETE_CHOICE.getKey()) != null ? map.get(EFapsKey.AUTOCOMPLETE_CHOICE.getKey()) : map.get(EFapsKey.AUTOCOMPLETE_VALUE.getKey()); final String value = map.get(EFapsKey.AUTOCOMPLETE_VALUE.getKey()); final JSONObject object = new JSONObject(); if (Type.SUGGESTION.equals(this.settings.getAutoType())) { if (this.settings.getMaxChoiceLength() > 0 && choice.length() > this.settings.getMaxChoiceLength()) { object.put("label", StringUtils.left(choice, this.settings.getMaxChoiceLength()) + "..."); } else { object.put("label", choice); } if (this.settings.getMaxValueLength() > 0 && value.length() > this.settings.getMaxValueLength()) { object.put("name", StringUtils.left(value, this.settings.getMaxChoiceLength()) + "..."); } else { object.put("name", value); } } else { object.put("id", key); if (this.settings.getMaxChoiceLength() > 0 && choice.length() > this.settings.getMaxChoiceLength()) { object.put("name", StringUtils.left(choice, this.settings.getMaxChoiceLength()) + "..."); } else { object.put("name", choice); } if (!choice.equals(value)) { if (this.settings.getMaxValueLength() > 0 && value.length() > this.settings.getMaxValueLength()) { object.put("label", StringUtils.left(value, this.settings.getMaxChoiceLength()) + "..."); } else { object.put("label", value); } } } jsonArray.put(object); i++; } if (!(i < this.settings.getMaxResult() || this.settings.getMaxResult() == -1)) { final JSONObject object = new JSONObject(); object.put("id", "MAXRESULT"); object.put("name", "..."); object.put("label", "..."); jsonArray.put(object); } _target.appendJSON(jsonArray.toString()); } catch (final JSONException e) { LOG.error("Catched JSONException", e); } }
From source file:org.finra.herd.core.HerdStringUtils.java
/** * Truncates the description field to a configurable value thereby producing a 'short description' * * @param description the specified description * @param shortDescMaxLength the short description maximum length * * @return truncated (short) description *//*from www .j a v a 2 s.c o m*/ public static String getShortDescription(String description, Integer shortDescMaxLength) { // Parse out only html tags, truncate and return // Do a partial HTML parse just in case there are some elements that don't have ending tags or the like String toParse = description != null ? description : ""; return StringUtils.left(Jsoup.parseBodyFragment(toParse).body().text(), shortDescMaxLength); }
From source file:org.finra.herd.rest.BusinessObjectDefinitionRestControllerIndexTest.java
@Test public void testIndexSearchBusinessObjectDefinitions() { // Create a new tag key with a tag type and a tag code TagKey tagKey = new TagKey(TAG_TYPE, TAG_CODE); // Create a new business object definition search key for use in the business object definition search key list BusinessObjectDefinitionSearchKey businessObjectDefinitionSearchKey = new BusinessObjectDefinitionSearchKey( tagKey, INCLUDE_TAG_HIERARCHY); // Create a new business object definition search key list with the tag key and the include tag hierarchy boolean flag List<BusinessObjectDefinitionSearchKey> businessObjectDefinitionSearchKeyList = new ArrayList<>(); businessObjectDefinitionSearchKeyList.add(businessObjectDefinitionSearchKey); // Create a new business object definition search filter list with the new business object definition search key list List<BusinessObjectDefinitionSearchFilter> businessObjectDefinitionSearchFilterList = new ArrayList<>(); businessObjectDefinitionSearchFilterList .add(new BusinessObjectDefinitionSearchFilter(false, businessObjectDefinitionSearchKeyList)); //Create a list of facet fields List<String> facetFields = new ArrayList<>(); facetFields.add("Invalid"); // Create a new business object definition search request that will be used when testing the index search business object definitions method BusinessObjectDefinitionIndexSearchRequest businessObjectDefinitionSearchRequest = new BusinessObjectDefinitionIndexSearchRequest( businessObjectDefinitionSearchFilterList, facetFields); // Create a new fields set that will be used when testing the index search business object definitions method Set<String> fields = Sets.newHashSet(FIELD_DATA_PROVIDER_NAME, FIELD_DISPLAY_NAME, FIELD_SHORT_DESCRIPTION); // Create a business object definition entity list to return from the search business object definitions by tags function List<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityList = new ArrayList<>(); businessObjectDefinitionEntityList.add(businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, BDEF_DESCRIPTION, businessObjectDefinitionServiceTestHelper.getNewAttributes())); businessObjectDefinitionEntityList.add(businessObjectDefinitionDaoTestHelper .createBusinessObjectDefinitionEntity(NAMESPACE, BDEF_NAME_2, DATA_PROVIDER_NAME_2, BDEF_DESCRIPTION_2, businessObjectDefinitionServiceTestHelper.getNewAttributes())); // Create a list to hold the business object definitions that will be returned as part of the search response List<BusinessObjectDefinition> businessObjectDefinitions = new ArrayList<>(); // Retrieve all unique business object definition entities and construct a list of business object definitions based on the requested fields. for (BusinessObjectDefinitionEntity businessObjectDefinitionEntity : ImmutableSet .copyOf(businessObjectDefinitionEntityList)) { // Convert the business object definition entity to a business object definition and add it to the list of business object definitions that will be // returned as a part of the search response BusinessObjectDefinition businessObjectDefinition = new BusinessObjectDefinition(); // Populate the business object definition businessObjectDefinition.setNamespace(businessObjectDefinitionEntity.getNamespace().getCode()); businessObjectDefinition.setBusinessObjectDefinitionName(businessObjectDefinitionEntity.getName()); businessObjectDefinition/*from w ww .ja va 2 s .c o m*/ .setDataProviderName(businessObjectDefinitionEntity.getDataProvider().getName()); businessObjectDefinition.setShortDescription( StringUtils.left(businessObjectDefinitionEntity.getDescription(), SHORT_DESCRIPTION_LENGTH)); businessObjectDefinition.setDisplayName(businessObjectDefinitionEntity.getDisplayName()); businessObjectDefinitions.add(businessObjectDefinition); } List<TagTypeIndexSearchResponseDto> tagTypeIndexSearchResponseDtos = new ArrayList<>(); List<TagIndexSearchResponseDto> tagIndexSearchResponseDtos = new ArrayList<>(); tagIndexSearchResponseDtos.add(new TagIndexSearchResponseDto(TAG_CODE, TAG_COUNT, TAG_DISPLAY_NAME)); tagIndexSearchResponseDtos.add(new TagIndexSearchResponseDto(TAG_CODE_2, TAG_COUNT, TAG_DISPLAY_NAME_2)); TagTypeIndexSearchResponseDto tagTypeIndexSearchResponseDto = new TagTypeIndexSearchResponseDto(TAG_TYPE, TAG_TYPE_COUNT, tagIndexSearchResponseDtos, TAG_TYPE_DISPLAY_NAME); tagTypeIndexSearchResponseDtos.add(tagTypeIndexSearchResponseDto); List<Facet> tagTypeFacets = new ArrayList<>(); for (TagTypeIndexSearchResponseDto tagTypeIndexSearchResponse : ImmutableSet .copyOf(tagTypeIndexSearchResponseDtos)) { List<Facet> tagFacets = new ArrayList<>(); for (TagIndexSearchResponseDto tagIndexSearchResponseDto : tagTypeIndexSearchResponse .getTagIndexSearchResponseDtos()) { Facet tagFacet = new Facet(tagIndexSearchResponseDto.getTagDisplayName(), tagIndexSearchResponseDto.getCount(), FacetTypeEnum.TAG.value(), tagIndexSearchResponseDto.getTagCode(), null); tagFacets.add(tagFacet); } tagTypeFacets.add( new Facet(tagTypeIndexSearchResponse.getDisplayName(), tagTypeIndexSearchResponse.getCount(), FacetTypeEnum.TAG_TYPE.value(), tagTypeIndexSearchResponse.getCode(), tagFacets)); } // Construct business object search response. BusinessObjectDefinitionIndexSearchResponse businessObjectDefinitionSearchResponse = new BusinessObjectDefinitionIndexSearchResponse(); businessObjectDefinitionSearchResponse.setBusinessObjectDefinitions(businessObjectDefinitions); businessObjectDefinitionSearchResponse.setFacets(tagTypeFacets); // Mock the call to the business object definition service when(businessObjectDefinitionService .indexSearchBusinessObjectDefinitions(businessObjectDefinitionSearchRequest, fields)) .thenReturn(businessObjectDefinitionSearchResponse); // Create a business object definition. BusinessObjectDefinitionIndexSearchResponse businessObjectDefinitionSearchResponseFromRestCall = businessObjectDefinitionRestController .indexSearchBusinessObjectDefinitions(fields, businessObjectDefinitionSearchRequest); // Verify the method call to businessObjectDefinitionService.indexAllBusinessObjectDefinitions() verify(businessObjectDefinitionService, times(1)) .indexSearchBusinessObjectDefinitions(businessObjectDefinitionSearchRequest, fields); // Validate the returned object. assertThat("Business object definition index search response was null.", businessObjectDefinitionSearchResponseFromRestCall, not(nullValue())); assertThat("Business object definition index search response was not correct.", businessObjectDefinitionSearchResponseFromRestCall, is(businessObjectDefinitionSearchResponse)); assertThat( "Business object definition index search response was not an instance of BusinessObjectDefinitionSearchResponse.class.", businessObjectDefinitionSearchResponseFromRestCall, instanceOf(BusinessObjectDefinitionIndexSearchResponse.class)); }
From source file:org.finra.herd.service.BusinessObjectDefinitionServiceTestHelper.java
/** * Creates a business object definition from a business object definition entity. * * @param businessObjectDefinitionEntity the specified business object definition entity * * @return the business object definition entity *///from w w w .ja v a 2 s. c om public BusinessObjectDefinition createBusinessObjectDefinitionFromEntityForSearchTesting( BusinessObjectDefinitionEntity businessObjectDefinitionEntity) { BusinessObjectDefinition businessObjectDefinition = new BusinessObjectDefinition(); businessObjectDefinition.setNamespace(businessObjectDefinitionEntity.getNamespace().getCode()); businessObjectDefinition.setBusinessObjectDefinitionName(businessObjectDefinitionEntity.getName()); businessObjectDefinition.setDataProviderName(businessObjectDefinitionEntity.getDataProvider().getName()); businessObjectDefinition.setDisplayName(businessObjectDefinitionEntity.getDisplayName()); String toParse = businessObjectDefinitionEntity.getDescription() != null ? businessObjectDefinitionEntity.getDescription() : ""; businessObjectDefinition.setShortDescription( StringUtils.left(Jsoup.parseBodyFragment(toParse).body().text(), configurationHelper.getProperty( ConfigurationValue.BUSINESS_OBJECT_DEFINITION_SHORT_DESCRIPTION_LENGTH, Integer.class))); return businessObjectDefinition; }
From source file:org.forgerock.openidm.repo.jdbc.impl.GenericSQLQueryFilterVisitor.java
private Object trimValue(final Object value) { // Must retain types for getPropTypeValueClause() if (isNumeric(value) || isBoolean(value)) { return value; } else {/*from w w w. j av a 2 s . co m*/ return StringUtils.left(value.toString(), searchableLength); } }
From source file:org.forgerock.openidm.repo.jdbc.impl.GenericTableHandler.java
/** * Internal recursive function to add/write properties. * If batching is enabled, prepared statements are added to the batch and only executed if they hit the max limit. * After completion returns the number of properties that have only been added to the batch but not yet executed. * The caller is responsible for executing the batch on remaining items when it deems the batch complete. * * If batching is not enabled, prepared statements are immediately executed. * * @param fullId the full URI of the resource the belongs to * @param dbId the generated identifier to link the properties table with the main table (foreign key) * @param localId the local identifier of the resource these properties belong to * @param value the JSON value with the properties to write * @param connection the DB connection//w ww. j a v a 2s . co m * @param propCreateStatement the prepared properties insert statement * @param batchingCount the current number of statements that have been batched and not yet executed on the prepared statement * @return status of the current batchingCount, i.e. how many statements are not yet executed in the PreparedStatement * @throws SQLException if the insert failed */ private int writeValueProperties(String fullId, long dbId, String localId, JsonValue value, Connection connection, PreparedStatement propCreateStatement, int batchingCount) throws SQLException { for (JsonValue entry : value) { JsonPointer propPointer = entry.getPointer(); if (cfg.isSearchable(propPointer)) { String propkey = propPointer.toString(); if (entry.isMap() || entry.isList()) { batchingCount = writeValueProperties(fullId, dbId, localId, entry, connection, propCreateStatement, batchingCount); } else { String propvalue = null; Object val = entry.getObject(); if (val != null) { propvalue = StringUtils.left(val.toString(), getSearchableLength()); } String proptype = null; if (propvalue != null) { proptype = entry.getObject().getClass().getName(); // TODO: proper type info } if (logger.isTraceEnabled()) { logger.trace("Populating statement {} with params {}, {}, {}, {}, {}", queryMap.get(QueryDefinition.PROPCREATEQUERYSTR), dbId, localId, propkey, proptype, propvalue); } propCreateStatement.setLong(1, dbId); propCreateStatement.setString(2, propkey); propCreateStatement.setString(3, proptype); propCreateStatement.setString(4, propvalue); logger.debug("Executing: {}", propCreateStatement); if (enableBatching) { propCreateStatement.addBatch(); batchingCount++; } else { int numUpdate = propCreateStatement.executeUpdate(); } if (logger.isTraceEnabled()) { logger.trace("Inserting objectproperty id: {} propkey: {} proptype: {}, propvalue: {}", fullId, propkey, proptype, propvalue); } } if (enableBatching && batchingCount >= maxBatchSize) { int[] numUpdates = propCreateStatement.executeBatch(); if (logger.isDebugEnabled()) { logger.debug("Batch limit reached, update of objectproperties updated: {}", Arrays.asList(numUpdates)); } propCreateStatement.clearBatch(); batchingCount = 0; } } } return batchingCount; }
From source file:org.forgerock.openidm.repo.jdbc.impl.query.TableQueries.java
private String trimValue(Object param) { return maxPropLen <= 0 ? param.toString() : StringUtils.left(param.toString(), maxPropLen); }
From source file:org.icgc.dcc.release.job.fathmm.core.FathmmPredictor.java
private static Map<String, String> result(Map<String, Object> facade, Map<String, Object> probability, String aaChange, String weights) { Map<String, String> result = newHashMap(); float W = Float.parseFloat(facade.get(StringUtils.left(aaChange, 1)).toString()); float M = Float.parseFloat(facade.get(StringUtils.right(aaChange, 1)).toString()); float D = Float.parseFloat(probability.get("disease").toString()) + 1.0f; float O = Float.parseFloat(probability.get("other").toString()) + 1.0f; // The original calculation is in log2(...), this is just to change basis double score = Math.log(((1.0 - W) * O) / ((1.0 - M) * D)) / Math.log(2); // This is intended as well, the original script rounds before comparing against the threshold score = Math.floor(score * 100) / 100; result = newHashMap();/*from w ww.ja v a 2s . c o m*/ result.put("HMM", (String) facade.get("id")); result.put("Description", (String) facade.get("description")); result.put("Position", facade.get("position").toString()); result.put("W", String.valueOf(W)); result.put("M", String.valueOf(M)); result.put("D", String.valueOf(D)); result.put("O", String.valueOf(O)); result.put("Score", String.valueOf(score)); if (weights.equals("INHERITED")) { if (score <= -1.5f) { result.put("Prediction", "DAMAGING"); } else { result.put("Prediction", "TOLERATED"); } } return result; }