use of org.apache.commons.lang.StringUtils in project sonarqube by SonarSource.
the class SetAction method handle.
@Override
public void handle(Request request, Response response) throws Exception {
String projectKey = request.mandatoryParam(PARAM_PROJECT);
List<String> tags = request.mandatoryParamAsStrings(PARAM_TAGS).stream().filter(StringUtils::isNotBlank).map(t -> t.toLowerCase(Locale.ENGLISH)).map(SetAction::checkTag).distinct().collect(Collectors.toList());
try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto project = componentFinder.getByKey(dbSession, projectKey);
checkRequest(project.isRootProject(), "Component must be a project");
userSession.checkComponentUuidPermission(UserRole.ADMIN, project.uuid());
project.setTags(tags);
dbClient.componentDao().updateTags(dbSession, project);
dbSession.commit();
indexers.forEach(i -> i.indexProject(project.uuid(), PROJECT_TAGS_UPDATE));
}
response.noContent();
}
use of org.apache.commons.lang.StringUtils in project ddf by codice.
the class OperationsMetacardSupport method guessMimeType.
// package-private for unit testing
String guessMimeType(String mimeTypeRaw, String fileName, Path tmpContentPath) throws IOException {
if (ContentItem.DEFAULT_MIME_TYPE.equals(mimeTypeRaw)) {
try (InputStream inputStreamMessageCopy = com.google.common.io.Files.asByteSource(tmpContentPath.toFile()).openStream()) {
String mimeTypeGuess = frameworkProperties.getMimeTypeMapper().guessMimeType(inputStreamMessageCopy, FilenameUtils.getExtension(fileName));
if (StringUtils.isNotEmpty(mimeTypeGuess)) {
mimeTypeRaw = mimeTypeGuess;
}
} catch (MimeTypeResolutionException e) {
LOGGER.debug("Unable to guess mime type for file.", e);
}
if (ContentItem.DEFAULT_MIME_TYPE.equals(mimeTypeRaw)) {
Detector detector = new DefaultProbDetector();
try (InputStream inputStreamMessageCopy = TikaInputStream.get(tmpContentPath)) {
MediaType mediaType = detector.detect(inputStreamMessageCopy, new Metadata());
mimeTypeRaw = mediaType.toString();
} catch (IOException e) {
LOGGER.debug("Unable to guess mime type for file.", e);
}
}
if (mimeTypeRaw.equals("text/plain")) {
try (InputStream inputStreamMessageCopy = com.google.common.io.Files.asByteSource(tmpContentPath.toFile()).openStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStreamMessageCopy, Charset.forName("UTF-8")))) {
String line = bufferedReader.lines().map(String::trim).filter(StringUtils::isNotEmpty).findFirst().orElse("");
if (line.startsWith("<")) {
mimeTypeRaw = "text/xml";
} else if (line.startsWith("{") || line.startsWith("[")) {
mimeTypeRaw = "application/json";
}
} catch (IOException e) {
LOGGER.debug("Unable to guess mime type for file.", e);
}
}
}
return mimeTypeRaw;
}
use of org.apache.commons.lang.StringUtils in project data-prep by Talend.
the class PreparationAPITest method testPreparationPreviewOnPreparationWithTrimAction_TDP_5057.
/**
* Verify a calculate time since preview after a trim step on a preparation
* see <a href="https://jira.talendforge.org/browse/TDP-5057">TDP-5057</a>
*/
@Test
public void testPreparationPreviewOnPreparationWithTrimAction_TDP_5057() throws IOException {
// Create a dataset from csv
final String datasetId = testClient.createDataset("preview/best_sad_songs_of_all_time.csv", "testPreview");
// Create a preparation
String preparationId = testClient.createPreparationFromDataset(datasetId, "testPrep", home.getId());
// apply trim action on the 8nd column to make this column date valid
Map<String, String> trimParameters = new HashMap<>();
trimParameters.put("create_new_column", "false");
trimParameters.put("padding_character", "whitespace");
trimParameters.put("scope", "column");
trimParameters.put("column_id", "0008");
trimParameters.put("column_name", "Added At");
trimParameters.put("row_id", "null");
testClient.applyAction(preparationId, Trim.TRIM_ACTION_NAME, trimParameters);
// check column is date valid after trim action
InputStream inputStream = testClient.getPreparation(preparationId).asInputStream();
mapper.getDeserializationConfig().without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
RowMetadata preparationContent = mapper.readValue(inputStream, Data.class).metadata;
List<PatternFrequency> patternFrequencies = preparationContent.getColumns().get(8).getStatistics().getPatternFrequencies();
assertTrue(patternFrequencies.stream().map(//
PatternFrequency::getPattern).anyMatch("yyyy-MM-dd"::equals));
// create a preview of calculate time since action
PreviewAddParameters previewAddParameters = new PreviewAddParameters();
previewAddParameters.setDatasetId(datasetId);
previewAddParameters.setPreparationId(preparationId);
previewAddParameters.setTdpIds(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
Action calculateTimeUntilAction = new Action();
calculateTimeUntilAction.setName(ComputeTimeSince.TIME_SINCE_ACTION_NAME);
MixedContentMap actionParameters = new MixedContentMap();
actionParameters.put("create_new_column", "true");
actionParameters.put("time_unit", "HOURS");
actionParameters.put("since_when", "now_server_side");
actionParameters.put("scope", "column");
actionParameters.put("column_id", "0008");
actionParameters.put("column_name", "Added At");
calculateTimeUntilAction.setParameters(actionParameters);
previewAddParameters.setActions(Collections.singletonList(calculateTimeUntilAction));
JsonPath jsonPath = given().contentType(//
ContentType.JSON).body(//
previewAddParameters).expect().statusCode(200).log().ifError().when().post(//
"/api/preparations/preview/add").jsonPath();
// check non empty value for the new column
assertEquals(//
"new preview column should contains values according to calculate time since action", //
0, jsonPath.getList("records.0009").stream().map(String::valueOf).filter(StringUtils::isBlank).count());
}
use of org.apache.commons.lang.StringUtils in project eol-globi-data by jhpoelen.
the class StudyImporterForHurlbert method importInteraction.
protected void importInteraction(Set<String> regions, Set<String> locales, Set<String> habitats, Record record, Study study, String preyTaxonName, String predatorName) throws StudyImporterException {
try {
Taxon predatorTaxon = new TaxonImpl(predatorName);
Specimen predatorSpecimen = nodeFactory.createSpecimen(study, predatorTaxon);
setBasisOfRecordAsLiterature(predatorSpecimen);
Taxon preyTaxon = new TaxonImpl(preyTaxonName);
String preyNameId = StringUtils.trim(columnValueOrNull(record, "Prey_Name_ITIS_ID"));
if (NumberUtils.isDigits(preyNameId)) {
preyTaxon.setExternalId(TaxonomyProvider.ITIS.getIdPrefix() + preyNameId);
}
Specimen preySpecimen = nodeFactory.createSpecimen(study, preyTaxon);
setBasisOfRecordAsLiterature(preySpecimen);
String preyStage = StringUtils.trim(columnValueOrNull(record, "Prey_Stage"));
if (StringUtils.isNotBlank(preyStage)) {
Term lifeStage = nodeFactory.getOrCreateLifeStage("HULBERT:" + StringUtils.replace(preyStage, " ", "_"), preyStage);
preySpecimen.setLifeStage(lifeStage);
}
String preyPart = StringUtils.trim(columnValueOrNull(record, "Prey_Part"));
if (StringUtils.isNotBlank(preyPart)) {
Term term = nodeFactory.getOrCreateBodyPart("HULBERT:" + StringUtils.replace(preyPart, " ", "_"), preyPart);
preySpecimen.setBodyPart(term);
}
Date date = addCollectionDate(record, study);
nodeFactory.setUnixEpochProperty(predatorSpecimen, date);
nodeFactory.setUnixEpochProperty(preySpecimen, date);
LocationImpl location = new LocationImpl(null, null, null, null);
String longitude = columnValueOrNull(record, "Longitude_dd");
String latitude = columnValueOrNull(record, "Latitude_dd");
if (NumberUtils.isNumber(latitude) && NumberUtils.isNumber(longitude)) {
try {
LatLng latLng = LocationUtil.parseLatLng(latitude, longitude);
String altitude = columnValueOrNull(record, "Altitude_mean_m");
Double altitudeD = NumberUtils.isNumber(altitude) ? Double.parseDouble(altitude) : null;
location = new LocationImpl(latLng.getLat(), latLng.getLng(), altitudeD, null);
} catch (InvalidLocationException e) {
getLogger().warn(study, "found invalid (lat,lng) pair: (" + latitude + "," + longitude + ")");
}
}
String locationRegion = columnValueOrNull(record, "Location_Region");
String locationSpecific = columnValueOrNull(record, "Location_Specific");
location.setLocality(StringUtils.join(Arrays.asList(locationRegion, locationSpecific), ":"));
Location locationNode = nodeFactory.getOrCreateLocation(location);
String habitat_type = columnValueOrNull(record, "Habitat_type");
List<Term> habitatList = Arrays.stream(StringUtils.split(StringUtils.defaultIfBlank(habitat_type, ""), ";")).map(StringUtils::trim).map(habitat -> new TermImpl(idForHabitat(habitat), habitat)).collect(Collectors.toList());
nodeFactory.addEnvironmentToLocation(locationNode, habitatList);
preySpecimen.caughtIn(locationNode);
predatorSpecimen.caughtIn(locationNode);
predatorSpecimen.ate(preySpecimen);
} catch (NodeFactoryException e) {
throw new StudyImporterException("failed to create interaction between [" + predatorName + "] and [" + preyTaxonName + "]", e);
}
}
use of org.apache.commons.lang.StringUtils in project symphony by b3log.
the class ArticleMgmtService method saveMarkdown.
/**
* Saves markdown file for the specified article.
*
* @param article the specified article
*/
public void saveMarkdown(final JSONObject article) {
if (Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE) || Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) || Article.ARTICLE_TYPE_C_BOOK == article.optInt(Article.ARTICLE_TYPE)) {
return;
}
final String dir = Symphonys.get("ipfs.dir");
if (StringUtils.isBlank(dir)) {
return;
}
final Path dirPath = Paths.get(dir);
try {
FileUtils.forceMkdir(dirPath.toFile());
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Creates dir [" + dirPath.toString() + "] for save markdown files failed", e);
return;
}
final String id = article.optString(Keys.OBJECT_ID);
final String authorName = article.optJSONObject(Article.ARTICLE_T_AUTHOR).optString(User.USER_NAME);
final Path mdPath = Paths.get(dir, "hacpai", authorName, id + ".md");
try {
if (mdPath.toFile().exists()) {
final FileTime lastModifiedTime = Files.getLastModifiedTime(mdPath);
if (lastModifiedTime.toMillis() + 1000 * 60 * 60 >= System.currentTimeMillis()) {
return;
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Gets last modified time of file [" + mdPath.toString() + "] failed", e);
return;
}
try {
final Map<String, Object> hexoFront = new LinkedHashMap<>();
hexoFront.put("title", article.optString(Article.ARTICLE_TITLE));
hexoFront.put("date", DateFormatUtils.format((Date) article.opt(Article.ARTICLE_CREATE_TIME), "yyyy-MM-dd HH:mm:ss"));
hexoFront.put("updated", DateFormatUtils.format((Date) article.opt(Article.ARTICLE_UPDATE_TIME), "yyyy-MM-dd HH:mm:ss"));
final List<String> tags = Arrays.stream(article.optString(Article.ARTICLE_TAGS).split(",")).filter(StringUtils::isNotBlank).map(String::trim).collect(Collectors.toList());
if (tags.isEmpty()) {
tags.add("Sym");
}
hexoFront.put("tags", tags);
final String text = new Yaml().dump(hexoFront).replaceAll("\n", Strings.LINE_SEPARATOR) + "---" + Strings.LINE_SEPARATOR + article.optString(Article.ARTICLE_T_ORIGINAL_CONTENT);
FileUtils.writeStringToFile(new File(mdPath.toString()), text, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Writes article to markdown file [" + mdPath.toString() + "] failed", e);
}
}
Aggregations