本文整理汇总了Java中javaslang.control.Try类的典型用法代码示例。如果您正苦于以下问题:Java Try类的具体用法?Java Try怎么用?Java Try使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Try类属于javaslang.control包,在下文中一共展示了Try类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getName
import javaslang.control.Try; //导入依赖的package包/类
@Override
public String getName(final UID uniqueId) {
Preconditions.checkNotNull(uniqueId, "A null uniqueIdGenerator is not valid");
final String name = Try
.of(() ->
uidToNameCache.get(uniqueId))
.getOrElseThrow(() ->
//exception will be a failure in the loaderwriter
new RuntimeException(String.format(
"uniqueIdGenerator %s should exist in the cache, something may have gone wrong with self population",
uniqueId.toAllForms())));
if (name == null) {
throw new RuntimeException(String.format(
"uniqueIdGenerator %s has a null value associated with it in the cache, something has gone wrong with the UID cache/tables as all UIDs should have a name",
uniqueId.toAllForms()));
}
return name;
}
示例2: create
import javaslang.control.Try; //导入依赖的package包/类
public static String create(
Injector injector,
String statUuid,
String statName,
StatisticType statisticType,
EventStoreTimeIntervalEnum interval,
String... fields){
StatisticConfiguration statisticConfigurationEntity = new StroomStatsStoreEntityBuilder(
statUuid,
statName,
statisticType,
interval,
StatisticRollUpType.ALL)
.addFields(fields)
.build();
SessionFactory sessionFactory = injector.getInstance(SessionFactory.class);
StroomStatsStoreEntityMarshaller statisticConfigurationMarshaller = injector.getInstance(StroomStatsStoreEntityMarshaller.class);
Try<StatisticConfiguration> statisticConfigurationEntityTry = StroomStatsStoreEntityHelper.addStatConfig(
sessionFactory, statisticConfigurationMarshaller, statisticConfigurationEntity);
return statisticConfigurationEntityTry.get().getUuid();
}
示例3: persistDummyStatisticConfigurations
import javaslang.control.Try; //导入依赖的package包/类
public static List<String> persistDummyStatisticConfigurations(
final List<StatisticConfiguration> statisticConfigurations,
final SessionFactory sessionFactory,
final StroomStatsStoreEntityMarshaller stroomStatsStoreEntityMarshaller) {
return statisticConfigurations.stream()
.map(statisticConfiguration -> {
Try<StatisticConfiguration> entity = StroomStatsStoreEntityHelper.addStatConfig(
sessionFactory,
stroomStatsStoreEntityMarshaller,
statisticConfiguration);
return entity.get().getUuid();
})
.collect(Collectors.toList());
}
示例4: getAuthentication
import javaslang.control.Try; //导入依赖的package包/类
@Override
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(jwtProperties.getToken().getSecret())
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Try.of(() ->
Arrays.stream(claims.get(jwtProperties.getToken().getPayload().getAuthoritiesKey()).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList())
).recover(ex ->
Collections.emptyList()
).get();
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
示例5: attemptAuthentication
import javaslang.control.Try; //导入依赖的package包/类
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
Optional<? extends AuthenticationRequestBody> requestBody = Try.of(() ->
Optional.ofNullable(new ObjectMapper().readValue(httpServletRequest.getInputStream(),
jwtSecurityProperties.getAuthenticationRequestBody()))
).recover(ex ->
Optional.empty()
).get();
final UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(requestBody.map(AuthenticationRequestBody::getLogin).orElse(null),
requestBody.map(AuthenticationRequestBody::getPassword).orElse(null));
token.setDetails(requestBody.map(AuthenticationRequestBody::isRememberMe));
return getAuthenticationManager().authenticate(token);
}
示例6: render
import javaslang.control.Try; //导入依赖的package包/类
/**
* Render method will write the rendered output utilizing the
* properties on the views class and the template specified by the
* views to the provided outputstream
* @param view
* @param locale
* @param outputStream
* @throws IOException
*/
public void render(View view, Locale locale, OutputStream outputStream) throws IOException {
logger.debug("rendering jade views {}", view);
final Map<String, Object> model = Try.of(() -> convert(view))
.recover(this::recoverFromObjectMapping)
.orElseThrow(Throwables::propagate);
logger.debug("views class converted into the following model {}", model);
Try.of(() -> cache.get(view.getClass()))
.andThen((config) -> {
logger.debug("rendering template with name {} and model {}", view.getTemplateName(), model);
final String rendered = config.renderTemplate(config.getTemplate(view.getTemplateName()), model);
outputStream.write(
rendered.getBytes(view.getCharset().or(Charset.defaultCharset())));
})
.onFailure(Throwables::propagate);
}
示例7: parseMooseDataCard
import javaslang.control.Try; //导入依赖的package包/类
private Try<MooseDataCard> parseMooseDataCard(final MultipartFile xmlFile) {
final String xmlFileName = xmlFile.getOriginalFilename();
try (final InputStream is = xmlFile.getInputStream()) {
LOG.debug("Starting to parse moose data card from file '{}'.", xmlFileName);
// A hacky way of transforming Swedish version of moose data card into conformance with
// Finnish schema version.
final String xmlContent = IOUtils.readLines(is, Constants.DEFAULT_ENCODING).stream()
.map(line -> line.replaceAll("Älginformationskort", "Hirvitietokortti"))
.collect(joining("\n"));
final ByteArrayInputStream bais = new ByteArrayInputStream(xmlContent.getBytes(Constants.DEFAULT_ENCODING));
final MooseDataCard mooseDataCard =
((MooseDataCardContainer) jaxbMarshaller.unmarshal(new StreamSource(bais))).getReport();
LOG.debug("Parsing of moose data card from file '{}' succeeded.", xmlFileName);
return Try.success(mooseDataCard);
} catch (final Exception e) {
LOG.warn("Parsing of moose data card from file '{}' failed: {}", xmlFileName, e.getMessage());
return Try.failure(parsingXmlFileOfMooseDataCardFailed(xmlFileName, e));
}
}
示例8: validate
import javaslang.control.Try; //导入依赖的package包/类
@Nonnull
public Validation<String, Tuple3<String, String, DateTime>> validate(@Nonnull final String filename) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(filename),
format("Filename was empty while expected to have extension %s", canonicalName()));
final Matcher matcher = this.filenamePattern.matcher(filename);
if (!matcher.matches()) {
return invalid(invalidFilename(filename, canonicalName()));
}
final String timestampStr = matcher.group(3);
return Try
.of(() -> DATE_FORMATTER.parseLocalDateTime(timestampStr).toDateTime(Constants.DEFAULT_TIMEZONE))
.map(timestamp -> Tuple.of(matcher.group(1), matcher.group(2), timestamp))
.<Validation<String, Tuple3<String, String, DateTime>>> map(Validation::valid)
.getOrElseGet(parseException -> invalid(invalidTimestampInXmlFileName(timestampStr)));
}
示例9: load
import javaslang.control.Try; //导入依赖的package包/类
@Override
public Map<String, Double> load(final PdhQuery query) throws Exception {
final Map<String, String> counterToKey = new LinkedHashMap<>();
final String object = query.getObject();
for(final String key : query.getKeys()) {
counterToKey.put(toPath(object, key), key);
}
final Map<String, Double> computed = Try
.of(() -> pdh.getFormattedValues(copyOf(counterToKey.keySet())))
.getOrElse(ImmutableMap::of);
final Map<String, Double> result = new HashMap<>();
for(final Map.Entry<String, Double> entry : computed.entrySet()) {
result.put(counterToKey.get(entry.getKey()), entry.getValue());
}
return result;
}
示例10: receive
import javaslang.control.Try; //导入依赖的package包/类
@Override
public Try<Boolean> receive(Event event) {
requireNonNull(event, "event must be defined.");
return Try.of(() -> {
long timeoutMillis = DURATION * 60000;
Future<Object> future = Patterns.ask(endpoint, new AbstractEventEndpointActor.EventFromEventBusWrapper(event), timeoutMillis);
Object result = Await.result(future, scala.concurrent.duration.Duration.create(DURATION, TimeUnit.MINUTES));
if (LOGGER.isDebugEnabled() && AbstractEventEndpointActor.NO_PROCESSED.equals(result)) {
LOGGER.debug("Following event ignored, drop it from queue:\n{}", Event.convertToPrettyJson(event));
}
if (result instanceof Throwable) {
throw new RuntimeException("Unable to process following event:\n"+ Event.convertToPrettyJson(event), (Throwable) result);
}
return result != null;
});
}
示例11: isAlreadyInserted
import javaslang.control.Try; //导入依赖的package包/类
protected boolean isAlreadyInserted(String type, String id) {
if (isBlank(type)) {
throw new IllegalArgumentException("type must be defined.");
}
if (isBlank(id)) {
throw new IllegalArgumentException("id must be defined.");
}
JsonParser parser = new JsonParser();
Request request = computeLookupRequest(type, id);
Try<HttpResponse> httpResponses = executeRequest(request);
Try<Boolean> exist = httpResponses.map(httpResponse -> {
String body = httpResponse.getBody();
JsonObject json = (JsonObject) parser.parse(body);
boolean res = json.getAsJsonObject(HITS_ATTRIBUTES).getAsJsonPrimitive("total").getAsInt() > 0;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Result {} exist for {} with id {}:\n{}", res ? "already" : "not", type, id, new GsonBuilder().setPrettyPrinting().create().toJson(json));
}
return res;
});
return exist.getOrElse(Boolean.FALSE);
}
示例12: parsesPersonNamesAsDisplayNameIfPresent
import javaslang.control.Try; //导入依赖的package包/类
@Test
public void parsesPersonNamesAsDisplayNameIfPresent() {
final String expectedName = "person names";
Graph graph = newGraph()
.withVertex(v -> v
.withType("person")
.withVre("ww")
.withProperty("wwperson_names", getPersonName("person", "names"))
).build();
WwPersonDisplayName instance = new WwPersonDisplayName();
Try<JsonNode> result = graph.traversal().V().union(instance.traversalJson()).next();
assertThat(result.get().asText(), equalTo(expectedName));
}
示例13: parsesTempNameAsDisplayNameIfPersonNamesIsEmpty
import javaslang.control.Try; //导入依赖的package包/类
@Test
public void parsesTempNameAsDisplayNameIfPersonNamesIsEmpty() {
final String tempName = "temp name";
Graph graph = newGraph()
.withVertex(v -> v
.withType("person")
.withVre("ww")
.withProperty("wwperson_names", "{\"list\": []}")
.withProperty("wwperson_tempName", tempName)
).build();
WwPersonDisplayName instance = new WwPersonDisplayName();
Try<JsonNode> result = graph.traversal().V().union(instance.traversalJson()).next();
assertThat(result.get().asText(), equalTo("[TEMP] " + tempName));
}
示例14: parsesTempNameAsDisplayNameIfPersonNamesIsNotPresent
import javaslang.control.Try; //导入依赖的package包/类
@Test
public void parsesTempNameAsDisplayNameIfPersonNamesIsNotPresent() {
final String tempName = "temp name";
Graph graph = newGraph()
.withVertex(v -> v
.withType("person")
.withVre("ww")
.withProperty("wwperson_tempName", tempName)
).build();
WwPersonDisplayName instance = new WwPersonDisplayName();
Try<JsonNode> result = graph.traversal().V().union(instance.traversalJson()).next();
assertThat(result.get().asText(), equalTo("[TEMP] " + tempName));
}
示例15: function
import javaslang.control.Try; //导入依赖的package包/类
private Try<String> function (ExecutorService executor, Boolean flag){
return Try.of(() -> {
if(flag) {
Thread.sleep(4000);
return "Good night";
}
else
return "Good morning";
});
}