List of usage examples for org.apache.commons.lang3.tuple Pair getValue
@Override
public R getValue()
Gets the value from this pair.
This method implements the Map.Entry interface returning the right element as the value.
From source file:org.apache.syncope.fit.core.reference.AuthenticationITCase.java
@Test public void testReadEntitlements() { // 1. as anonymous (not allowed) try {//from ww w .j a va 2 s .c o m clientFactory.createAnonymous().self(); fail(); } catch (AccessControlException e) { assertNotNull(e); } // 2. as authenticated anonymous (used by admin console) Pair<Map<String, Set<String>>, UserTO> self = clientFactory.create(ANONYMOUS_UNAME, ANONYMOUS_KEY).self(); assertEquals(1, self.getKey().size()); assertTrue(self.getKey().keySet().contains(Entitlement.ANONYMOUS)); assertEquals(ANONYMOUS_UNAME, self.getValue().getUsername()); // 3. as admin self = adminClient.self(); assertEquals(Entitlement.values().size() - 1, self.getKey().size()); assertFalse(self.getKey().keySet().contains(Entitlement.ANONYMOUS)); assertEquals(ADMIN_UNAME, self.getValue().getUsername()); // 4. as user self = clientFactory.create("bellini", ADMIN_PWD).self(); assertFalse(self.getKey().isEmpty()); assertFalse(self.getKey().keySet().contains(Entitlement.ANONYMOUS)); assertEquals("bellini", self.getValue().getUsername()); }
From source file:org.apache.syncope.fit.core.reference.AuthenticationITCase.java
@Test public void issueSYNCOPE434() { Assume.assumeTrue(ActivitiDetector.isActivitiEnabledForUsers(syncopeService)); // 1. create user with group 9 (users with group 9 are defined in workflow as subject to approval) UserTO userTO = UserITCase.getUniqueSampleTO("createWithReject@syncope.apache.org"); MembershipTO membershipTO = new MembershipTO(); membershipTO.setRightKey(9L);/*from www .jav a 2 s. c o m*/ userTO.getMemberships().add(membershipTO); userTO = createUser(userTO); assertNotNull(userTO); assertEquals("createApproval", userTO.getStatus()); // 2. try to authenticate: fail try { clientFactory.create(userTO.getUsername(), "password123").self(); fail(); } catch (AccessControlException e) { assertNotNull(e); } // 3. approve user WorkflowFormTO form = userWorkflowService.getFormForUser(userTO.getKey()); form = userWorkflowService.claimForm(form.getTaskId()); Map<String, WorkflowFormPropertyTO> props = form.getPropertyMap(); props.get("approve").setValue(Boolean.TRUE.toString()); form.getProperties().clear(); form.getProperties().addAll(props.values()); userTO = userWorkflowService.submitForm(form); assertNotNull(userTO); assertEquals("active", userTO.getStatus()); // 4. try to authenticate again: success Pair<Map<String, Set<String>>, UserTO> self = clientFactory.create(userTO.getUsername(), "password123") .self(); assertNotNull(self); assertNotNull(self.getKey()); assertNotNull(self.getValue()); }
From source file:org.apache.syncope.fit.core.reference.UserSelfITCase.java
@Test public void read() { UserService userService2 = clientFactory.create("rossini", ADMIN_PWD).getService(UserService.class); try {//from w w w.j a va 2s .c o m userService2.read(1L); fail(); } catch (AccessControlException e) { assertNotNull(e); } Pair<Map<String, Set<String>>, UserTO> self = clientFactory.create("rossini", ADMIN_PWD).self(); assertEquals("rossini", self.getValue().getUsername()); }
From source file:org.apache.syncope.fit.core.UserSelfITCase.java
@Test public void read() { UserService userService2 = clientFactory.create("rossini", ADMIN_PWD).getService(UserService.class); try {//from www . ja va 2 s. c om userService2.read("1417acbe-cbf6-4277-9372-e75e04f97000"); fail("This should not happen"); } catch (ForbiddenException e) { assertNotNull(e); } Pair<Map<String, Set<String>>, UserTO> self = clientFactory.create("rossini", ADMIN_PWD).self(); assertEquals("rossini", self.getValue().getUsername()); }
From source file:org.apache.syncope.fit.core.UserSelfITCase.java
@Test public void authenticateByPlainAttribute() { UserTO rossini = userService.read("rossini"); assertNotNull(rossini);//from w w w.ja v a 2 s .c o m String userId = rossini.getPlainAttr("userId").get().getValues().get(0); assertNotNull(userId); Pair<Map<String, Set<String>>, UserTO> self = clientFactory.create(userId, ADMIN_PWD).self(); assertEquals(rossini.getUsername(), self.getValue().getUsername()); }
From source file:org.apache.tika.eval.AbstractProfiler.java
void unicodeBlocks(Metadata metadata, Map<Cols, String> data) { String content = getContent(metadata); if (content.length() < 200) { return;//from w ww .ja v a 2 s .c o m } String s = content; if (content.length() > maxContentLengthForLangId) { s = content.substring(0, maxContentLengthForLangId); } Map<String, Integer> m = new HashMap<>(); Reader r = new StringReader(s); try { int c = r.read(); while (c != -1) { Character.UnicodeBlock block = Character.UnicodeBlock.of(c); String blockString = (block == null) ? "NULL" : block.toString(); Integer i = m.get(blockString); if (i == null) { i = 0; } i++; if (block == null) { blockString = "NULL"; } m.put(blockString, i); c = r.read(); } } catch (IOException e) { e.printStackTrace(); //swallow } List<Pair<String, Integer>> pairs = new ArrayList<>(); for (Map.Entry<String, Integer> e : m.entrySet()) { pairs.add(Pair.of(e.getKey(), e.getValue())); } Collections.sort(pairs, new Comparator<Pair<String, Integer>>() { @Override public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } }); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 20 && i < pairs.size(); i++) { if (i > 0) { sb.append(" | "); } sb.append(pairs.get(i).getKey() + ": " + pairs.get(i).getValue()); } data.put(Cols.UNICODE_CHAR_BLOCKS, sb.toString()); }
From source file:org.asqatasun.rules.elementchecker.ElementCheckerImpl.java
/** * //from w w w .ja va 2 s . c o m * @param successSolutionPair * @param failureSolutionPair * @param eeAttributeNameList */ public ElementCheckerImpl(Pair<TestSolution, String> successSolutionPair, Pair<TestSolution, String> failureSolutionPair, String... eeAttributeNameList) { this.successSolutionPair.left = successSolutionPair.getKey(); this.successSolutionPair.right = successSolutionPair.getValue(); this.failureSolutionPair.left = failureSolutionPair.getKey(); this.failureSolutionPair.right = failureSolutionPair.getValue(); this.eeAttributeNames = Arrays.copyOf(eeAttributeNameList, eeAttributeNameList.length); }
From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java
/** sendEmail method sends email after receiving input parameters */ @Override/*from www.j a va2 s .c om*/ public void sendEmail(String fromEmail, String toEmail, String subject, String body, List<Pair<String, InputStream>> attachments) throws IOException { notNull(fromEmail, "fromEmail must be non-null"); notNull(toEmail, "toEmail must be non-null"); notNull(subject, "subject must be non-null"); notNull(body, "body must be non-null"); notNull(attachments, "attachments must be non-null"); if (StringUtils.isBlank(mailHost)) { throw new IOException("the mail server hostname has not been configured"); } List<File> tempFiles = new LinkedList<>(); try { InternetAddress emailAddr = new InternetAddress(toEmail); emailAddr.validate(); Properties properties = createSessionProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(fromEmail)); mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr); mimeMessage.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Holder<Long> bytesWritten = new Holder<>(0L); for (Pair<String, InputStream> attachment : attachments) { messageBodyPart = new MimeBodyPart(); File file = File.createTempFile("email-sender-", ".dat"); tempFiles.add(file); copyDataToTempFile(file, attachment.getValue(), bytesWritten); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file))); messageBodyPart.setFileName(attachment.getKey()); multipart.addBodyPart(messageBodyPart); } mimeMessage.setContent(multipart); send(mimeMessage); LOGGER.debug("Email sent to " + toEmail); } catch (AddressException e) { throw new IOException("invalid email address: email=" + toEmail, e); } catch (MessagingException e) { throw new IOException("message error occurred on send", e); } finally { tempFiles.forEach(file -> { if (!file.delete()) { LOGGER.debug("unable to delete tmp file: path={}", file); } }); } }
From source file:org.codice.ddf.catalog.sourcepoller.Poller.java
/** * @throws IllegalStateException if unable to wait for polls * @throws InterruptedException if the current thread was interrupted * @throws CancellationException if the task to wait for the loader {@link Callable<V>} to be * complete was cancelled/*from ww w .j a va2 s . co m*/ * @throws ExecutionException if the the task to wait for the loader {@link Callable<V>} threw an * exception * @throws PollerException if unable to commit the value for any of the {@code itemsToPoll} */ private void doPollItems(long timeout, TimeUnit timeoutTimeUnit, ImmutableMap<K, Callable<V>> itemsToPoll) throws InterruptedException, ExecutionException, PollerException { removeNoncurrentKeysFromTheCache(itemsToPoll.keySet()); if (itemsToPoll.isEmpty()) { LOGGER.debug("itemsToPoll is empty. Nothing to poll"); return; } // Gather any exceptions while loading or committing new values final Map<K, Throwable> exceptions = new HashMap<>(); final CompletionService<Pair<K, Commitable>> completionService = new ExecutorCompletionService<>( pollTimeoutWatcherThreadPool); final int startedLoadsCount = startLoads(timeout, timeoutTimeUnit, itemsToPoll, completionService, exceptions); boolean interrupted = false; try { for (int i = 0; i < startedLoadsCount; i++) { // Use CompletionService#poll(long, TimeUnit) instead of CompletionService#take() even // though the timeout has already been accounted for in #load(K, Callable<V>, long, // TimeUnit) to prevent blocking forever // @throws InterruptedException if interrupted while waiting final Future<Pair<K, Commitable>> nextCompletedLoadFuture = completionService.poll(timeout, timeoutTimeUnit); if (nextCompletedLoadFuture == null) { final String message = String.format("Unable to wait for polls to finish within %d %s", timeout, timeoutTimeUnit); LOGGER.debug(message); throw new IllegalStateException(message); } // @throws CancellationException if the computation was cancelled // @throws ExecutionException if the computation threw an exception // @throws InterruptedException if the current thread was interrupted final Pair<K, Commitable> nextCompletedLoad = nextCompletedLoadFuture.get(); try { attemptToCommitLoadedValue(nextCompletedLoad.getKey(), nextCompletedLoad.getValue(), exceptions); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } if (!exceptions.isEmpty()) { throw new PollerException(exceptions); } }
From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java
@Test @SuppressWarnings({ "unchecked" }) public void testParseAttachments() throws IOException, CatalogTransformerException, SourceUnavailableException, IngestException, InvalidSyntaxException { CatalogFramework framework = givenCatalogFramework(); BundleContext bundleContext = mock(BundleContext.class); Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>(); ServiceReference serviceReference = mock(ServiceReference.class); InputTransformer inputTransformer = mock(InputTransformer.class); MetacardImpl metacard = new MetacardImpl(); metacard.setMetadata("Some Text Again"); when(inputTransformer.transform(any())).thenReturn(metacard); when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer); serviceReferences.add(serviceReference); when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences); CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {//w w w .j ava2 s.com @Override BundleContext getBundleContext() { return bundleContext; } }; when(attributeRegistry.lookup(Core.METADATA)) .thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA))); when(attributeRegistry.lookup("foo")).thenReturn(Optional.empty()); addMatchingService(catalogServiceImpl, Collections.singletonList(getSimpleTransformer())); List<Attachment> attachments = new ArrayList<>(); ContentDisposition contentDisposition = new ContentDisposition( "form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt"); Attachment attachment = new Attachment("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), contentDisposition); attachments.add(attachment); ContentDisposition contentDisposition1 = new ContentDisposition( "form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml"); Attachment attachment1 = new Attachment("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), contentDisposition1); attachments.add(attachment1); Pair<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments, "xml"); assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again")); ContentDisposition contentDisposition2 = new ContentDisposition( "form-data; name=metadata; filename=C:\\DDF\\metacard.xml"); Attachment attachment2 = new Attachment("metadata", new ByteArrayInputStream("<meta>beta</meta>".getBytes()), contentDisposition2); attachments.add(attachment2); ContentDisposition contentDisposition3 = new ContentDisposition( "form-data; name=foo; filename=C:\\DDF\\metacard.xml"); Attachment attachment3 = new Attachment("foo", new ByteArrayInputStream("bar".getBytes()), contentDisposition3); attachments.add(attachment3); attachmentInfoAndMetacard = catalogServiceImpl.parseAttachments(attachments, "xml"); assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("<meta>beta</meta>")); assertThat(attachmentInfoAndMetacard.getValue().getAttribute("foo"), equalTo(null)); }