private AttributeQueryRequestDto createAttributeQuery(List<UserAccountCreationAttribute> userAccountCreationAttributes) { MatchingServiceConfigEntityDataDto matchingServiceConfig = matchingServiceConfigProxy.getMatchingService(state.getMatchingServiceAdapterEntityId()); return AttributeQueryRequestDto.createUserAccountRequiredMatchingServiceRequest( state.getRequestId(), state.getEncryptedMatchingDatasetAssertion(), state.getAuthnStatementAssertion(), Optional.<Cycle3Dataset>absent(), state.getRequestIssuerEntityId(), state.getAssertionConsumerServiceUri(), state.getMatchingServiceAdapterEntityId(), DateTime.now().plus(policyConfiguration.getMatchingServiceResponseWaitPeriod()), state.getIdpLevelOfAssurance(), userAccountCreationAttributes, state.getPersistentId(), assertionRestrictionFactory.getAssertionExpiry(), matchingServiceConfig.getUserAccountCreationUri(), matchingServiceConfig.isOnboarding() ); }
@Test public void mapGraphValue_ReturnsEmptyResult_WhenNoValueHasBeenDefined() { // Arrange Value value = null; // Act Object result = schemaMapperAdapter.mapGraphValue(arrayProperty, contextMock, ValueContext.builder().value(value).build(), schemaMapperAdapter); // Assert assertThat(result, instanceOf(List.class)); List<Optional<String>> list = (List) result; assertThat(list, empty()); }
public EidasAttributeQueryRequestDto build() { return new EidasAttributeQueryRequestDto( "requestId", "authnRequestIssuesEntityId", URI.create("assertionConsumerServiceUri"), DateTime.now().plusHours(2), "matchingServiceAdapterEntityId", URI.create("matchingServiceAdapterUri"), DateTime.now().plusHours(1), true, LevelOfAssurance.LEVEL_2, new PersistentId("nameId"), Optional.of(aCycle3Dataset()), Optional.absent(), "encryptedIdentityAssertion" ); }
@Test public void testGetGroupsForUsers() { User user = new User(); Group group = new Group(); group.setId(GROUPID); Set<Group> groups = new HashSet<>(); Set<GroupDTO> groupDTOS = new HashSet<>(); groupDTOS.add(getGroupResponse()); groups.add(group); user.setGroups(groups); Mockito.when(userDAO.getUserWithGroups(Matchers.anyLong())).thenReturn(Optional.fromNullable(user)); Response response = controller.getGroupsForUser(user); Response validResponse = Response.status(Response.Status.OK).entity(groupDTOS).build(); assertEquals(response.getStatus(), validResponse.getStatus()); assertEquals(response.getEntity(), validResponse.getEntity()); }
@Test public void getNextState_shouldMaintainRelayState() throws Exception { final String relayState = "4x100m"; UserAccountCreationRequestSentState state = aUserAccountCreationRequestSentState() .withRelayState(Optional.of(relayState)) .build(); UserAccountCreationRequestSentStateController controller = new UserAccountCreationRequestSentStateController(state, null, eventSinkHubEventLogger, null, levelOfAssuranceValidator, null, null); UserAccountCreatedFromMatchingService userAccountCreatedFromMatchingService = new UserAccountCreatedFromMatchingService("issuer-id", "", "", Optional.<LevelOfAssurance>absent()); final State newState = controller.getNextStateForUserAccountCreated(userAccountCreatedFromMatchingService); assertThat(newState).isInstanceOf(UserAccountCreatedState.class); final UserAccountCreatedState userAccountCreatedState = (UserAccountCreatedState)newState; assertThat(userAccountCreatedState.getRelayState()).isNotNull(); assertThat(userAccountCreatedState.getRelayState().isPresent()).isTrue(); assertThat(userAccountCreatedState.getRelayState().get()).isEqualTo(relayState); }
/** * Gets the State of the Tweet by checking the InputStream. * For a sample Bing Maps API response, please check the snippet at the end of this file. * * @param inputStream Bing Maps API response. * @return State of the Tweet as got from Bing Maps API reponse. */ @SuppressWarnings("unchecked") private final static Optional<String> getStateFromJSONResponse(InputStream inputStream) { final ObjectMapper mapper = new ObjectMapper(); try { //final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(new File("C:/BingMaps_JSON_Response.json"), Map.class); final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(inputStream, Map.class); if(200 == Integer.parseInt(String.valueOf(bingResponse.get("statusCode")))) { final List<Map<String, Object>> resourceSets = (List<Map<String, Object>>) bingResponse.get("resourceSets"); if(resourceSets != null && resourceSets.size() > 0){ final List<Map<String, Object>> resources = (List<Map<String, Object>>) resourceSets.get(0).get("resources"); if(resources != null && resources.size() > 0){ final Map<String, Object> address = (Map<String, Object>) resources.get(0).get("address"); LOGGER.debug("State==>{}", address.get("adminDistrict")); return Optional.of((String) address.get("adminDistrict")); } } } } catch (final IOException ioException) { LOGGER.error(ioException.getMessage(), ioException); ioException.printStackTrace(); } return Optional.absent(); }
private void setDisplayedItemWithUpdate(@Nullable ItemStack stack, boolean p_174864_2_) { if (stack != null) { stack = stack.copy(); stack.stackSize = 1; stack.setItemFrame(this); } this.getDataManager().set(ITEM, Optional.fromNullable(stack)); this.getDataManager().setDirty(ITEM); if (stack != null) { this.playSound(SoundEvents.ENTITY_ITEMFRAME_ADD_ITEM, 1.0F, 1.0F); } if (p_174864_2_ && this.hangingPosition != null) { this.worldObj.updateComparatorOutputLevel(this.hangingPosition, Blocks.AIR); } }
@Override public void initializeCache() { Optional<? extends IN4JSEclipseProject> projectOpt = null; IN4JSEclipseProject n4jsProject = null; for (IProject project : workspace.getRoot().getProjects()) { projectOpt = eclipseCore.create(project); if (projectOpt.isPresent()) { n4jsProject = projectOpt.get(); if (n4jsProject.exists()) { updateCache(n4jsProject); } } } Listener listener = new Listener(); workspace.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE); }
public Element toXml(final Document doc, final Object result, final OperationExecution execution) throws DocumentedException { AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper() .prepareStrategy(execution.getReturnType()); Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result); Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, execution.getReturnType().getOpenType()); // FIXME: multiple return values defined as leaf-list and list in yang should // not be wrapped in output xml element, // they need to be appended directly under rpc-reply element // // Either allow List of Elements to be returned from NetconfOperation or // pass reference to parent output xml element for netconf operations to // append result(s) on their own Element tempParent = XmlUtil.createElement(doc, "output", Optional.of(XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); new ObjectXmlWriter().prepareWritingStrategy(execution.getReturnType().getAttributeYangName(), execution.getReturnType(), doc) .writeElement(tempParent, execution.getNamespace(), mappedAttributeOpt.get()); XmlElement xmlElement = XmlElement.fromDomElement(tempParent); return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement(); }
@Value.Lazy public Optional<ValueImmutableInfo> features() { Optional<ValueImmutableInfo> immutableAnnotation = ImmutableMirror.find(element()).transform(ToImmutableInfo.FUNCTION); if (immutableAnnotation.isPresent()) { return immutableAnnotation; } for (String a : environment().round().customImmutableAnnotations()) { if (isAnnotatedWith(element(), a)) { return Optional.of(environment().defaultStyles().defaults()); } } return Optional.absent(); }
@Test public void build() throws Exception { Map<String, String> map = new HashMap<>(); map.put("attribute", "attributeValue"); EidasAttributeQueryRequestDto eidasAttributeQueryRequestDto = EidasAttributeQueryRequestDtoBuilder.anEidasAttributeQueryRequestDto().build(); assertThat(eidasAttributeQueryRequestDto.getRequestId()).isEqualTo("requestId"); assertThat(eidasAttributeQueryRequestDto.getPersistentId()).isEqualTo(new PersistentId("nameId")); assertThat(eidasAttributeQueryRequestDto.getEncryptedIdentityAssertion()).isEqualTo("encryptedIdentityAssertion"); assertThat(eidasAttributeQueryRequestDto.getAssertionConsumerServiceUri()).isEqualTo(URI.create("assertionConsumerServiceUri")); assertThat(eidasAttributeQueryRequestDto.getAuthnRequestIssuerEntityId()).isEqualTo("authnRequestIssuesEntityId"); assertThat(eidasAttributeQueryRequestDto.getLevelOfAssurance()).isEqualTo(LevelOfAssurance.LEVEL_2); assertThat(eidasAttributeQueryRequestDto.getAttributeQueryUri()).isEqualTo(URI.create("matchingServiceAdapterUri")); assertThat(eidasAttributeQueryRequestDto.getMatchingServiceEntityId()).isEqualTo("matchingServiceAdapterEntityId"); assertThat(eidasAttributeQueryRequestDto.getMatchingServiceRequestTimeOut()).isEqualTo(DateTime.now().plusHours(1)); assertThat(eidasAttributeQueryRequestDto.isOnboarding()).isTrue(); assertThat(eidasAttributeQueryRequestDto.getCycle3Dataset()).isEqualTo(Optional.of(new Cycle3Dataset(map))); assertThat(eidasAttributeQueryRequestDto.getUserAccountCreationAttributes()).isEqualTo(Optional.absent()); assertThat(eidasAttributeQueryRequestDto.getAssertionExpiry()).isEqualTo(DateTime.now().plusHours(2)); }
@Override public Optional<Long> sizeIfKnown() { BasicFileAttributes attrs; try { attrs = readAttributes(); } catch (IOException e) { // Failed to get attributes; we don't know the size. return Optional.absent(); } // Don't return a size for directories or symbolic links; their sizes are implementation // specific and they can't be read as bytes using the read methods anyway. if (attrs.isDirectory() || attrs.isSymbolicLink()) { return Optional.absent(); } return Optional.of(attrs.size()); }
private void recursiveCollectRlFromChain(IN4JSProject runtimeEnvironment, Collection<IN4JSProject> collection) { Optional<String> extended = runtimeEnvironment.getExtendedRuntimeEnvironmentId(); if (extended.isPresent()) { String id = extended.get(); List<IN4JSProject> extendedRE = from(getAllProjects()).filter(p -> id.equals(p.getProjectId())) .toList(); if (extendedRE.isEmpty()) { return; } if (extendedRE.size() > 1) { LOGGER.debug("multiple projects match id " + id); LOGGER.error(new RuntimeException("Cannot obtain transitive list of provided libraries")); return; } IN4JSProject extendedRuntimeEnvironemnt = extendedRE.get(0); recursiveProvidedRuntimeLibrariesCollector(extendedRuntimeEnvironemnt.getProvidedRuntimeLibraries(), collection, p -> isRuntimeLibrary(p)); recursiveCollectRlFromChain(extendedRuntimeEnvironemnt, collection); } }
public ReceivedAuthnRequest( String id, String issuer, DateTime issueInstant, Optional<Boolean> forceAuthentication, URI assertionConsumerServiceUri, Optional<String> relayState, DateTime receivedTime, String principalIpAddress) { this.id = id; this.issuer = issuer; this.issueInstant = issueInstant; this.forceAuthentication = forceAuthentication; this.assertionConsumerServiceUri = assertionConsumerServiceUri; this.relayState = relayState; this.receivedTime = receivedTime; this.principalIpAddress = principalIpAddress; }
@Override public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) { if (uri.isArchive()) { URIBasedStorage storage = new URIBasedStorage(uri); String authority = uri.authority(); URI archiveFileURI = URI.createURI(authority.substring(0, authority.length() - 1)); Optional<? extends IN4JSEclipseProject> optionalProject = eclipseCore.findProject(archiveFileURI); if (optionalProject.isPresent()) { return Collections.singletonList(Tuples.<IStorage, IProject> create(storage, optionalProject.get() .getProject())); } else { return Collections.singletonList(Tuples.create(storage, null)); } } else { return Collections.emptyList(); } }
private DocLevelEventArg resolveToERE(final EREDocument doc, final EREAligner ereAligner, final Response response) { numResponses.add(errKey(response)); final Symbol realis = Symbol.from(response.realis().name()); final Optional<ScoringCorefID> alignedCorefIDOpt = ereAligner.argumentForResponse(response); if (!alignedCorefIDOpt.isPresent()) { log.info("Alignment failed for {}", response); mentionAlignmentFailuresB.put(errKey(response), response.toString()); } // this increments the alignment failure ID regardless of success or failure, but // we don't care final ScoringCorefID alignedCorefID = alignedCorefIDOpt.or( // in case of alignment failure, we make a pseudo-entity from the CAS offsets // it will always be wrong, but will be consistent for the same extent appearing in // different event roles new ScoringCorefID.Builder().scoringEntityType(ScoringEntityType.AlignmentFailure) .withinTypeID(response.canonicalArgument().charOffsetSpan().asCharOffsetRange().toString()) .build()); return new DocLevelEventArg.Builder().docID(Symbol.from(doc.getDocId())) .eventType(response.type()).eventArgumentType(response.role()) .corefID(alignedCorefID.globalID()).realis(realis).build(); }
private void tryValidateManifest(final IResourceDelta delta) { final String fullPath = delta.getFullPath().toString(); final URI folderUri = URI.createPlatformResourceURI(fullPath, true); final IN4JSProject project = core.findProject(folderUri).orNull(); if (null != project && project.exists()) { final URI manifestLocation = project.getManifestLocation().orNull(); if (null != manifestLocation) { final IFile manifest = delta.getResource().getProject().getFile(N4MF_MANIFEST); final ResourceSet resourceSet = core.createResourceSet(Optional.of(project)); final Resource resource = resourceSet.getResource(manifestLocation, true); final Job job = Job.create("", monitor -> { validatorExtension.updateValidationMarkers(manifest, resource, ALL, monitor); return OK_STATUS; }); job.setPriority(INTERACTIVE); job.schedule(); } } }
private Optional<String> getCompatibleStepNameFrom(Method testMethod) { Annotation[] annotations = testMethod.getAnnotations(); for (Annotation annotation : annotations) { if (isACompatibleStep(annotation)) { try { String annotationType = annotation.annotationType() .getSimpleName(); String annotatedValue = (String) annotation.getClass() .getMethod("value").invoke(annotation); if (StringUtils.isEmpty(annotatedValue)) { return Optional.absent(); } else { return Optional.of(annotationType + " " + StringUtils .uncapitalize(annotatedValue)); } } catch (Exception ignoredException) { } } } return Optional.absent(); }
private TestSuiteResponse obtainExpectedResponse(IfExpression rule) { TestSuiteResponse response = new TestSuiteResponse(); for (Expressions expressions : RulesUtils.getReturn(rule)) { if (expressions instanceof Server) { Optional<String> path = Optional.fromNullable(((Server) expressions).getPath()); if (path.or("").contains("/")) { XreStackPath stackPath = new XreStackPath(path.get() + "/" + serviceName); response.setFlavor(stackPath.getFlavor()); response.setXreStack(stackPath.getStackOnlyPath()); } else { response.setFlavor(path.or("")); } response.setRule(rule.getId()); return response; } else { log.warn("Rule {} is skipped. ServerGroup is not supported", rule.getId()); } } return null; }
@Test public void testRemoveServerForwardToLeader() { LOG.info("testRemoveServerForwardToLeader starting"); DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl(); configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); ActorRef leaderActor = actorFactory.createTestActor( MessageCollectorActor.props(), actorFactory.generateActorId(LEADER_ID)); TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor( MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID, leaderActor.path().toString())).config(configParams).persistent(Optional.of(false)) .props().withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(FOLLOWER_ID)); followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete(); followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(), -1, -1, (short)0), leaderActor); followerRaftActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef()); expectFirstMatching(leaderActor, RemoveServer.class); LOG.info("testRemoveServerForwardToLeader ending"); }
@Test public void shouldGetCycle3AttributeRequestDataFromConfiguration() throws JsonProcessingException { final SessionId sessionId = SessionIdBuilder.aSessionId().build(); final String rpEntityId = new EidasCycle3DTO(sessionId).getRequestIssuerEntityId(); final Response sessionCreatedResponse = createSessionInEidasAwaitingCycle3DataState(sessionId); assertThat(sessionCreatedResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); final MatchingProcessDto cycle3Attribute = new MatchingProcessDto(Optional.of("TUFTY_CLUB_CARD")); configStub.setUpStubForEnteringAwaitingCycle3DataState(rpEntityId, cycle3Attribute); samlSoapProxyProxyStub.setUpStubForSendHubMatchingServiceRequest(sessionId); final Cycle3AttributeRequestData actualResponse = getCycle3Data(sessionId); final Cycle3AttributeRequestData expectedResponse = aCycle3AttributeRequestData() .withAttributeName(cycle3Attribute.getAttributeName().get()) .withRequestIssuerId(rpEntityId) .build(); assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse); }
private static NormalizedNode<?, ?> getCars(final ShardDataTree shardDataTree) { final ReadOnlyShardDataTreeTransaction readOnlyShardDataTreeTransaction = shardDataTree.newReadOnlyTransaction(nextTransactionId()); final DataTreeSnapshot snapshot1 = readOnlyShardDataTreeTransaction.getSnapshot(); final Optional<NormalizedNode<?, ?>> optional = snapshot1.readNode(CarsModel.BASE_PATH); assertEquals(true, optional.isPresent()); return optional.get(); }
private Optional<JobRunId> getFirstJobRunForJob(JobId jobId) { for (int i = 0; i < 10; ++i) { List<JobRunId> jobRunIds = this.apiClient.getJobRunsForJob(jobId); if (jobRunIds.size() > 0) { return Optional.of(jobRunIds.get(0)); } } return Optional.absent(); }
/** * Gets the optional {@link Player} joining, this will load lazily. * * @return the {@link Player} or {@link Optional#absent()} or if offline */ public Optional<Player> getPlayer() { if (this.player == null) { this.player = Optional.fromNullable(Bukkit.getPlayer(this.playerUUID)); } return this.player; }
private User getUserFromID(String userID) { long id = Long.parseLong(userID); Optional<User> user = userDAO.find(id); if (!user.isPresent()) { String error = String.format(AdminErrorMessage.DOES_NOT_EXIST, userErrorString); throw new WebApplicationException(error, Response.Status.BAD_REQUEST); } return user.get(); }
public SamlMessage generateAuthnResponseFromHub(SessionId sessionId, String principalIpAddressAsSeenByHub) { AuthnResponseFromHubContainerDto authnResponseFromHub = sessionProxy.getAuthnResponseFromHub(sessionId); Response samlResponse = responseTransformer.apply(authnResponseFromHub.getSamlResponse()); validateAndLogSamlResponseSignature(samlResponse); SamlMessage samlMessage = new SamlMessage(authnResponseFromHub.getSamlResponse(), SamlMessageType.SAML_RESPONSE, authnResponseFromHub.getRelayState(), authnResponseFromHub.getPostEndpoint().toString(), Optional.<Boolean>absent()); externalCommunicationEventLogger.logResponseFromHub(samlResponse.getID(), sessionId, authnResponseFromHub.getPostEndpoint(), principalIpAddressAsSeenByHub); return samlMessage; }
public Result build(List<String> lines) { boolean matches = true; List<String> remainingLines = new ArrayList<>(lines); Optional<String> mismatchDescription = Optional.absent(); for (Link link : subLinks) { Result result = link.filterMatching(remainingLines); matches = matches && result.matches; remainingLines = result.remainingLines; mismatchDescription = append(mismatchDescription, result.mismatchDescription); } return new Result(matches, remainingLines, mismatchDescription); }
@Test public void validate_shouldThrowExceptionIfLevelOfAssuranceFromMatchingServiceDoesNotExist() throws Exception { LevelOfAssurance levelOfAssurance = LevelOfAssurance.LEVEL_2; try { levelOfAssuranceValidator.validate(Optional.<LevelOfAssurance>absent(), levelOfAssurance); fail("fail"); } catch (StateProcessingValidationException e) { assertThat(e.getMessage()).isEqualTo(StateProcessingValidationException.noLevelOfAssurance().getMessage()); } }
@Override public void registerDataChangeListener(YangInstanceIdentifier path, AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener, DataChangeScope scope, Optional<DataTreeCandidate> initialState, Consumer<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>> onRegistration) { publisherActor().tell(new ShardDataChangePublisherActor.RegisterListener(path, listener, scope, initialState, onRegistration), ActorRef.noSender()); }
/** * Returns the children of this node, in left-to-right order. */ @Override public final Iterable<T> children(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { boolean doneLeft; boolean doneRight; @Override protected T computeNext() { if (!doneLeft) { doneLeft = true; Optional<T> left = leftChild(root); if (left.isPresent()) { return left.get(); } } if (!doneRight) { doneRight = true; Optional<T> right = rightChild(root); if (right.isPresent()) { return right.get(); } } return endOfData(); } }; } @Override public void forEach(Consumer<? super T> action) { acceptIfPresent(action, leftChild(root)); acceptIfPresent(action, rightChild(root)); } }; }
@Test public void testIsUserAnAdminWithInvalidID() { long id = 12; Optional<User> user = Optional.of(new User()); Mockito.when(userDAO.find(id)).thenReturn(user); Response response = resources.client().target(isUserAnAdminUrl + id).request().get(); ResponseValidator.validate(response, 204); }
public static Iterable<Layout> allLayouts(final Acceleration acceleration) { final LayoutContainer aggContainer = Optional.fromNullable(acceleration.getAggregationLayouts()).or(EMPTY_CONTAINER); final LayoutContainer rawContainer = Optional.fromNullable(acceleration.getRawLayouts()).or(EMPTY_CONTAINER); final Iterable<Layout> aggLayouts = AccelerationUtils.selfOrEmpty(aggContainer.getLayoutList()); final Iterable<Layout> rawLayouts = AccelerationUtils.selfOrEmpty(rawContainer.getLayoutList()); return Iterables.concat(aggLayouts, rawLayouts); }
public Optional<Player> getPlayer() { if (this.player == null) { this.player = Optional.fromNullable(Bukkit.getPlayer(this.playerUUID)); } return this.player; }
@Test public void toResponse_shouldAuditException() throws Exception { URI exceptionUri = URI.create("/exception-uri"); ApplicationException exception = createUnauditedException(exceptionType, errorId, exceptionUri); mapper.toResponse(exception); verify(exceptionAuditor).auditException(exception, Optional.of(sessionId)); }
/** * For an identifier of the form "a.b.c.d", returns "a.b.c" * For an identifier of the form "a", returns absent */ public Optional<QualifiedName> getPrefix() { if (parts.size() == 1) { return Optional.absent(); } return Optional.of(QualifiedName.of(parts.subList(0, parts.size() - 1))); }
public void setOwner(EntityLivingBase owner) { // TODO Auto-generated method stub this.owner = owner; if (owner instanceof EntityPlayer){ this.ownerName = owner.getName(); this.dataManager.set(OWNER_UUID, Optional.of(owner.getUniqueID())); this.enablePersistence(); } else if(owner != null) this.engMade = true; }
/** * The new materialization is only as fresh as the most stale input materialization. This method finds which of the * input materializations has the earliest expiration. The new materialization's expiration must be equal to or sooner * than this. * @return the earliest expiration. if no accelerations, Long.MAX_VALUE is returned */ private Optional<Long> getFirstExpiration() { if (jobRef.get().getJobAttempt().getInfo().getAcceleration() == null) { return Optional.absent(); } List<Substitution> substitutions = jobRef.get().getJobAttempt().getInfo().getAcceleration().getSubstitutionsList(); if (substitutions == null || substitutions.isEmpty()) { return Optional.absent(); } return Optional.of(FluentIterable.from(substitutions) .transform(new Function<Substitution, Long>() { @Nullable @Override public Long apply(Substitution substitution) { List<String> path = substitution.getTablePathList(); final String layoutId = path.get(1); assert layoutId.equals(substitution.getId().getLayoutId()) : String.format("Layouts not equal. Layout id1: %s, Layout id2: %s", layoutId, substitution.getId().getLayoutId()); final String materializationId = path.get(2); List<Materialization> materializationList = context.materializationStore.get(new LayoutId(layoutId)).get().getMaterializationList(); Materialization materialization = Iterables.find(materializationList, new Predicate<Materialization>() { @Override public boolean apply(@Nullable Materialization materialization) { return materialization.getId().getId().equals(materializationId); } }, null); if (materialization == null || materialization.getExpiration() == null) { return 0L; } return materialization.getExpiration(); } }) .toSortedList(new Comparator<Long>() { @Override public int compare(Long o1, Long o2) { return o1.compareTo(o2); } }) .get(0)); // the list is guaranteed to be non-empty because of check at beginning of method. }
@Test public void shouldUpdateIfDimensionsBiggerThanCurrentlyStored() throws Exception { int colorIndex = 0; maximizedStickieSizeStorage.updateIfBiggerThanExisting(colorIndex, new StickieSize(111, 222)); maximizedStickieSizeStorage.updateIfBiggerThanExisting(colorIndex, new StickieSize(333, 444)); Optional<StickieSize> optionalStickieSize = maximizedStickieSizeStorage.getSizeOfMaximizedStickie(colorIndex); assertSizes(optionalStickieSize, 333, 444); }
@Test public void testGetSimulationCanvas_canvasIsNull() { // given when(createJsLoader.getContent()).thenReturn(createJsContent); // when Optional<Element> simulationElemrnt = simulationCanvasProvider.getSimulationCanvasElement(createJsLoader); // then assertFalse(simulationElemrnt.isPresent()); }
private void saveLayoutMaterializationFailedState(Layout layout) { Optional<MaterializedLayout> materializedLayoutOpt = context.getMaterializationStore().get(layout.getId()); if (materializedLayoutOpt.isPresent()) { MaterializedLayout materializedLayout = materializedLayoutOpt.get(); materializedLayout.setState(MaterializedLayoutState.FAILED); context.getMaterializationStore().save(materializedLayout); } }