src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
Protocol { public String writeCommand(String command, Argument args) throws IOException, ProtocolException { String tag = tagPrefix + Integer.toString(tagCounter++); output.writeBytes(tag + " " + command); if (args != null) { output.write(' '); args.write(this); } output.write(CRLF); output.flush(); return tag; } Proto...
@Test public void testTagPrefixReuse() throws IOException, ProtocolException { Properties props = new Properties(); props.setProperty("mail.imap.reusetagprefix", "true"); Protocol p = new Protocol(nullis, nullps, props, false); String tag = p.writeCommand("CMD", null); assertEquals("A0", tag); p = new Protocol(nullis, ...
ResponseInputStream { public ByteArray readResponse() throws IOException { return readResponse(null); } ResponseInputStream(InputStream in); ByteArray readResponse(); ByteArray readResponse(ByteArray ba); int available(); }
@Test public void testEofWhileReadingLiteral() throws Exception { ByteArrayInputStream bis = new ByteArrayInputStream( "test{1}\r\n".getBytes("ISO-8859-1")); ResponseInputStream ris = new ResponseInputStream(bis); try { ris.readResponse(); } catch (IOException ex) { return; } fail("no exception"); }
IMAPProtocol extends Protocol { public BODY fetchBody(int msgno, String section) throws ProtocolException { return fetchBody(msgno, section, false); } IMAPProtocol(String name, String host, int port, Properties props, boolean isSSL, MailLogger logger); IMAPProtocol(InputStream in, PrintStream out, Properties pr...
@Test public void testMultipleBodyResponses() throws Exception { Properties props = new Properties(); props.setProperty("mail.imap.reusetagprefix", "true"); IMAPProtocol p = new IMAPProtocol( new AsciiStringInputStream(response), new PrintStream(new ByteArrayOutputStream()), props, debug); BODY b = p.fetchBody(1, "1.1"...
IMAPStore extends Store implements QuotaAwareStore, ResponseHandler { @Override public Folder[] getSharedNamespaces() throws MessagingException { Namespaces ns = getNamespaces(); if (ns == null || ns.shared == null) return super.getSharedNamespaces(); return namespaceToFolders(ns.shared, null); } IMAPStore(Session sess...
@Test public void testUtf7Namespaces() { testWithHandler( new IMAPTest() { @Override public void test(Store store, TestServer server) throws MessagingException, IOException { store.connect("test", "test"); Folder[] pub = ((IMAPStore)store).getSharedNamespaces(); assertEquals(utf8Folder, pub[0].getName()); } }, new IMAP...
IMAPStore extends Store implements QuotaAwareStore, ResponseHandler { @Override public synchronized Folder getFolder(String name) throws MessagingException { checkConnected(); return newIMAPFolder(name, IMAPFolder.UNKNOWN_SEPARATOR); } IMAPStore(Session session, URLName url); protected IMAPStore(Session session, URLNa...
@Test public void testUtf8FolderNameCreate() { testWithHandler( new IMAPTest() { @Override public void test(Store store, TestServer server) throws MessagingException, IOException { store.connect("test", "test"); Folder test = store.getFolder(utf8Folder); assertTrue(test.create(Folder.HOLDS_MESSAGES)); } }, new IMAPUtf8...
IMAPMessage extends MimeMessage implements ReadableMime { @Override public int getSize() throws MessagingException { checkExpunged(); if (size == -1) loadEnvelope(); if (size > Integer.MAX_VALUE) return Integer.MAX_VALUE; else return (int)size; } protected IMAPMessage(IMAPFolder folder, int msgnum); protected IMAPMes...
@Test public void testSizeSmall() { testWithHandler( new IMAPTest() { @Override public void test(Folder folder, IMAPHandlerMessage handler) throws MessagingException { Message m = folder.getMessage(1); assertEquals(123, m.getSize()); } }, new IMAPHandlerMessage() { {{ size = 123; }} }); }
IMAPMessage extends MimeMessage implements ReadableMime { @Override public String getFileName() throws MessagingException { checkExpunged(); if (bodyLoaded) return super.getFileName(); String filename = null; loadBODYSTRUCTURE(); if (bs.dParams != null) filename = bs.dParams.get("filename"); if (filename == null && bs....
@Test public void testAttachementFileName() { testWithHandler( new IMAPTest() { @Override public void test(Folder folder, IMAPHandlerMessage handler) throws MessagingException, IOException { Message m = folder.getMessage(1); Multipart mp = (Multipart)m.getContent(); BodyPart bp = mp.getBodyPart(1); assertEquals("filena...
IMAPMessage extends MimeMessage implements ReadableMime { @Override public String getSubject() throws MessagingException { checkExpunged(); if (bodyLoaded) return super.getSubject(); if (subject != null) return subject; loadEnvelope(); if (envelope.subject == null) return null; try { subject = MimeUtility.decodeText(Mi...
@Test public void testUtf8SubjectEncoded() { String s = null; try { s = MimeUtility.decodeText(ENV_UTF8_ENCODED_SUBJECT); } catch (UnsupportedEncodingException ex) { } final String subject = s; testWithHandler( new IMAPTest() { @Override public void test(Folder folder, IMAPHandlerMessage handler) throws MessagingExcept...
ContentType { public boolean match(ContentType cType) { if (!((primaryType == null && cType.getPrimaryType() == null) || (primaryType != null && primaryType.equalsIgnoreCase(cType.getPrimaryType())))) return false; String sType = cType.getSubType(); if ((subType != null && subType.startsWith("*")) || (sType != null && ...
@Test public void testMatch() throws Exception { ContentType empty = new ContentType(); assertFalse(empty.match("text/plain")); ContentType plain = new ContentType("text/plain"); assertTrue(plain.match("text/plain")); assertFalse(empty.match(plain)); assertFalse(plain.match(empty)); assertTrue(plain.match("text/*")); C...
MimeBodyPart extends BodyPart implements MimePart { @Override public void setDataHandler(DataHandler dh) throws MessagingException { this.dh = dh; cachedContent = null; MimeBodyPart.invalidateContentHeaders(this); } MimeBodyPart(); MimeBodyPart(InputStream is); MimeBodyPart(InternetHeaders headers, byte[] content); @...
@Test public void testSetDataHandler() throws Exception { Session s = Session.getInstance(new Properties()); MimeMessage orig = createMessage(s); MimeMultipart omp = (MimeMultipart)orig.getContent(); MimeBodyPart obp = (MimeBodyPart)omp.getBodyPart(0); final DataHandler odh = obp.getDataHandler(); MimeMessage msg = new...
MimeBodyPart extends BodyPart implements MimePart { @Override public boolean isMimeType(String mimeType) throws MessagingException { return isMimeType(this, mimeType); } MimeBodyPart(); MimeBodyPart(InputStream is); MimeBodyPart(InternetHeaders headers, byte[] content); @Override int getSize(); @Override int getLineC...
@Test public void testIsMimeTypeBadParameter() throws Exception { String part = "Content-Type: application/x-test; type=a/b\n" + "\n" + "\n"; MimeBodyPart mbp = new MimeBodyPart(new AsciiStringInputStream(part)); assertTrue("complete MIME type", mbp.isMimeType("application/x-test")); assertTrue("pattern MIME type", mbp...
MailDateFormat extends SimpleDateFormat { @Override public StringBuffer format(Date date, StringBuffer dateStrBuf, FieldPosition fieldPosition) { return super.format(date, dateStrBuf, fieldPosition); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, StringBuffer dateStrBuf, ...
@Test() public void formatMustThrowNpeForNullArgs() { for (int mask = 0; mask < 7; mask++) { try { Date date = (mask & 1) == 1 ? new Date() : null; StringBuffer toAppendTo = (mask & 2) == 2 ? new StringBuffer() : null; FieldPosition pos = (mask & 4) == 4 ? new FieldPosition(0) : null; getDefault().format(date, toAppend...
MailDateFormat extends SimpleDateFormat { @Override public Date parse(String text, ParsePosition pos) { if (text == null || pos == null) { throw new NullPointerException(); } else if (0 > pos.getIndex() || pos.getIndex() >= text.length()) { return null; } return isLenient() ? new Rfc2822LenientParser(text, pos).parse()...
@Test public void parseMustThrowNpeForNullArgs() { for (int mask = 0; mask < 3; mask++) { try { String source = (mask & 1) == 1 ? "1 Jan 2015 00:00 +0100" : null; ParsePosition pos = (mask & 2) == 2 ? new ParsePosition(0) : null; getDefault().parse(source, pos); fail("No NullPointerException thrown for mask = " + mask)...
MailDateFormat extends SimpleDateFormat { @Override public void setCalendar(Calendar newCalendar) { throw new UnsupportedOperationException("Method " + "setCalendar() shouldn't be called"); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, StringBuffer dateStrBuf, ...
@Test(expected = UnsupportedOperationException.class) public void mustProhibitSetCalendar() { getDefault().setCalendar(Calendar.getInstance()); }
MailDateFormat extends SimpleDateFormat { @Override public void setNumberFormat(NumberFormat newNumberFormat) { throw new UnsupportedOperationException("Method " + "setNumberFormat() shouldn't be called"); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, StringBuffer dateSt...
@Test(expected = UnsupportedOperationException.class) public void mustProhibitSetNumberFormat() { getDefault().setNumberFormat(NumberFormat.getInstance()); }
MailDateFormat extends SimpleDateFormat { @Override public Date get2DigitYearStart() { throw new UnsupportedOperationException("Method " + "get2DigitYearStart() shouldn't be called"); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, StringBuffer dateStrBuf, Fiel...
@Test(expected = UnsupportedOperationException.class) public void mustProhibitGet2DigitYearStart() { getDefault().get2DigitYearStart(); }
MailDateFormat extends SimpleDateFormat { @Override public void set2DigitYearStart(Date startDate) { throw new UnsupportedOperationException("Method " + "set2DigitYearStart() shouldn't be called"); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, StringBuffer dateStrBuf, ...
@Test(expected = UnsupportedOperationException.class) public void mustProhibitSet2DigitYearStart() { getDefault().set2DigitYearStart(new Date()); }
MailDateFormat extends SimpleDateFormat { @Override public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) { throw new UnsupportedOperationException("Method " + "setDateFormatSymbols() shouldn't be called"); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, Str...
@Test(expected = UnsupportedOperationException.class) public void mustProhibitSetDateFormatSymbols() { SimpleDateFormat fmt = getStrict(); fmt.setDateFormatSymbols(new DateFormatSymbols(Locale.FRENCH)); Date date = mustPass(fmt, "1 Jan 2015 00:00:00 +0000"); assertThatDate(date, "jeu., 1 janv. 2015 00:00:00 +0000 (UTC)...
MimeMessage extends Message implements MimePart { @Override public Address[] getRecipients(Message.RecipientType type) throws MessagingException { if (type == RecipientType.NEWSGROUPS) { String s = getHeader("Newsgroups", ","); return (s == null) ? null : NewsAddress.parse(s); } else return getAddressHeader(getHeaderNa...
@Test public void testSetRecipientStringNull() throws Exception { String addr = "joe@example.com"; MimeMessage m = new MimeMessage(s); m.setRecipient(TO, new InternetAddress(addr)); assertEquals("To: is set", addr, m.getRecipients(TO)[0].toString()); m.setRecipient(TO, (Address)null); assertArrayEquals("To: is removed"...
MimeMessage extends Message implements MimePart { @Override public String[] getHeader(String name) throws MessagingException { return headers.getHeader(name); } MimeMessage(Session session); MimeMessage(Session session, InputStream is); MimeMessage(MimeMessage source); protected MimeMessage(Folder folder, int msgnum...
@Test public void testSetNewsgroupWhitespace() throws Exception { NewsAddress addr = new NewsAddress("alt.\r\nbad"); MimeMessage m = new MimeMessage(s); m.setRecipient(NEWSGROUPS, addr); assertEquals("alt.bad", m.getHeader("Newsgroups", null)); }
MimeMessage extends Message implements MimePart { @Override public synchronized void setDataHandler(DataHandler dh) throws MessagingException { this.dh = dh; cachedContent = null; MimeBodyPart.invalidateContentHeaders(this); } MimeMessage(Session session); MimeMessage(Session session, InputStream is); MimeMessage(Mim...
@Test public void testSetDataHandler() throws Exception { Session s = Session.getInstance(new Properties()); MimeMessage orig = createMessage(s); final DataHandler odh = orig.getDataHandler(); MimeMessage msg = new MimeMessage(s) { { dh = odh; } }; msg = new MimeMessage(msg); assertEquals("text/x-test", msg.getContentT...
InternetHeaders { public String[] getHeader(String name) { Iterator<InternetHeader> e = headers.iterator(); List<String> v = new ArrayList<>(); while (e.hasNext()) { InternetHeader h = e.next(); if (name.equalsIgnoreCase(h.getName()) && h.line != null) { v.add(h.getValue()); } } if (v.size() == 0) return (null); String...
@Test public void testContinuationLine() throws Exception { String header = "Subject: a\r\n b\r\n\r\n"; InternetHeaders ih = new InternetHeaders( new AsciiStringInputStream(header)); assertEquals(1, ih.getHeader("Subject").length); assertEquals("a\r\n b", ih.getHeader("Subject")[0]); }
InternetHeaders { public void load(InputStream is) throws MessagingException { load(is, false); } InternetHeaders(); InternetHeaders(InputStream is); InternetHeaders(InputStream is, boolean allowutf8); void load(InputStream is); void load(InputStream is, boolean allowutf8); String[] getHeader(String name); String get...
@Test public void testInitialWhitespaceLineLoad() throws Exception { InternetHeaders ih = new InternetHeaders(); ih.load(new AsciiStringInputStream(initialWhitespaceHeader)); testInitialWhitespaceLine(ih); } @Test public void testInitialContinuationLineLoad() throws Exception { InternetHeaders ih = new InternetHeaders(...
MimeUtility { public static String decodeWord(String eword) throws ParseException, UnsupportedEncodingException { if (!eword.startsWith("=?")) throw new ParseException( "encoded word does not start with \"=?\": " + eword); int start = 2; int pos; if ((pos = eword.indexOf('?', start)) == -1) throw new ParseException( "e...
@Test public void testBadChineseCharsets() throws Exception { String badgb2312 = "=?gb2312?B?xbfUqqLjIChFVVIpttK7u4EwhDYgKENOWSk=?="; String badgbk = "=?gbk?B?xbfUqqLjIChFVVIpttK7u4EwhDYgKENOWSk=?="; String badms936 = "=?ms936?B?xbfUqqLjIChFVVIpttK7u4EwhDYgKENOWSk=?="; String badcp936 = "=?cp936?B?xbfUqqLjIChFVVIpttK7u...
URLName { public String getFile() { return file; } URLName( String protocol, String host, int port, String file, String username, String password ); URLName(URL url); URLName(String url); @Override String toString(); int getPort(); String getProtocol(); String getFile(); String getRef(); String getHost(); Stri...
@Test public void testFile() throws Exception { URLName u = new URLName("http: assertEquals("file", u.getFile()); u = new URLName("http: assertEquals("file", u.getFile()); u = new URLName("http: assertEquals("", u.getFile()); u = new URLName("http: assertEquals(null, u.getFile()); u = new URLName("http: assertEquals(nu...
LogManagerProperties extends Properties { static long parseDurationToMillis(final CharSequence value) throws Exception { try { final Class<?> k = findClass("java.time.Duration"); final Method parse = k.getMethod("parse", CharSequence.class); if (!k.isAssignableFrom(parse.getReturnType()) || !Modifier.isStatic(parse.get...
@Test public void testParseDurationMs() throws Exception { try { long ms = LogManagerProperties.parseDurationToMillis("PT0.345S"); assertEquals(345L, ms); } catch (ClassNotFoundException | NoClassDefFoundError ignore) { assertFalse(ignore.toString(), hasJavaTimeModule()); } } @Test public void testParseDurationSec() th...
LogManagerProperties extends Properties { @Override public synchronized Object get(final Object key) { Object value; if (key instanceof String) { value = getProperty((String) key); } else { value = null; } if (value == null) { value = defaults.get(key); if (value == null && !defaults.containsKey(key)) { value = super.g...
@Test public void testGet() throws Exception { String prefix = LogManagerPropertiesTest.class.getName(); LogManager manager = LogManager.getLogManager(); try { String key = prefix.concat(".dummy"); Properties parent = new Properties(); parent.put(key, "value"); parent.put("", "empty"); read(manager, parent); parent = n...
LogManagerProperties extends Properties { @Override public synchronized boolean containsKey(final Object key) { boolean found = key instanceof String && getProperty((String) key) != null; if (!found) { found = defaults.containsKey(key) || super.containsKey(key); } return found; } LogManagerProperties(final Properties p...
@Test public void testContainsKey() throws Exception { String prefix = LogManagerPropertiesTest.class.getName(); LogManager manager = LogManager.getLogManager(); try { String key = prefix.concat(".dummy"); Properties parent = new Properties(); parent.put(key, "value"); parent.put("", "empty"); read(manager, parent); pa...
LogManagerProperties extends Properties { @Override public synchronized Object remove(final Object key) { final Object def = preWrite(key); final Object man = super.remove(key); return man == null ? def : man; } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesnt...
@Test public void testRemove() throws Exception { String prefix = LogManagerPropertiesTest.class.getName(); LogManager manager = LogManager.getLogManager(); try { String key = prefix.concat(".dummy"); Properties parent = new Properties(); parent.put(key, "value"); parent.put("", "empty"); read(manager, parent); parent ...
LogManagerProperties extends Properties { @Override public synchronized Object put(final Object key, final Object value) { if (key instanceof String && value instanceof String) { final Object def = preWrite(key); final Object man = super.put(key, value); return man == null ? def : man; } else { return super.put(key, va...
@Test public void testPut() throws Exception { String prefix = LogManagerPropertiesTest.class.getName(); LogManager manager = LogManager.getLogManager(); try { String key = prefix.concat(".dummy"); Properties parent = new Properties(); parent.put(key, "value"); parent.put("", "empty"); read(manager, parent); parent = n...
LogManagerProperties extends Properties { @Override public Object setProperty(String key, String value) { return this.put(key, value); } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String...
@Test public void testSetProperty() throws Exception { String prefix = LogManagerPropertiesTest.class.getName(); LogManager manager = LogManager.getLogManager(); try { String key = prefix.concat(".dummy"); Properties parent = new Properties(); parent.put(key, "value"); parent.put("", "empty"); read(manager, parent); pa...
LogManagerProperties extends Properties { static String toLanguageTag(final Locale locale) { final String l = locale.getLanguage(); final String c = locale.getCountry(); final String v = locale.getVariant(); final char[] b = new char[l.length() + c.length() + v.length() + 2]; int count = l.length(); l.getChars(0, count...
@Test public void testToLanguageTag() throws Exception { assertEquals("en-US", LogManagerProperties.toLanguageTag(Locale.US)); assertEquals("en", LogManagerProperties.toLanguageTag(Locale.ENGLISH)); assertEquals("", LogManagerProperties.toLanguageTag(new Locale("", "", ""))); Locale l = new Locale("en", "US", "slang");...
LogManagerProperties extends Properties { @SuppressWarnings("unchecked") static Comparator<? super LogRecord> newComparator(String name) throws Exception { return newObjectFrom(name, Comparator.class); } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSupe...
@Test public void testNewComparator() throws Exception { try { LogManagerProperties.newComparator(null); fail("Null was allowed."); } catch (NullPointerException expect) { } try { LogManagerProperties.newComparator(""); fail("Empty class was allowed."); } catch (ClassNotFoundException expect) { } try { LogManagerProper...
LogManagerProperties extends Properties { @SuppressWarnings({"unchecked", "ThrowableResultIgnored"}) static <T> Comparator<T> reverseOrder(final Comparator<T> c) { if (c == null) { throw new NullPointerException(); } Comparator<T> reverse = null; try { final Method m = c.getClass().getMethod("reversed"); if (!Modifier....
@Test public void testReverseOrder() throws Exception { try { LogManagerProperties.reverseOrder(null); fail("Null was allowed."); } catch (NullPointerException expect) { } Comparator<LogRecord> c = new ErrorComparator(); Comparator<LogRecord> r = LogManagerProperties.reverseOrder(c); assertTrue(c.getClass() != r.getCla...
LogManagerProperties extends Properties { static ErrorManager newErrorManager(String name) throws Exception { return newObjectFrom(name, ErrorManager.class); } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Overr...
@Test public void testNewErrorManager() throws Exception { try { LogManagerProperties.newErrorManager(null); fail("Null was allowed."); } catch (NullPointerException expect) { } try { LogManagerProperties.newErrorManager(""); fail("Empty class was allowed."); } catch (ClassNotFoundException expect) { } try { LogManager...
LogManagerProperties extends Properties { static Filter newFilter(String name) throws Exception { return newObjectFrom(name, Filter.class); } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized S...
@Test public void testNewFilter() throws Exception { try { LogManagerProperties.newFilter(null); fail("Null was allowed."); } catch (NullPointerException expect) { } try { LogManagerProperties.newFilter(""); fail("Empty class was allowed."); } catch (ClassNotFoundException expect) { } try { LogManagerProperties.newFilt...
LogManagerProperties extends Properties { static Formatter newFormatter(String name) throws Exception { return newObjectFrom(name, Formatter.class); } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synch...
@Test public void testNewFormatter() throws Exception { try { LogManagerProperties.newFormatter(null); fail("Null was allowed."); } catch (NullPointerException expect) { } try { LogManagerProperties.newFormatter(""); fail("Empty class was allowed."); } catch (ClassNotFoundException expect) { } try { LogManagerPropertie...
LogManagerProperties extends Properties { @SuppressWarnings("UseSpecificCatch") static Comparable<?> getZonedDateTime(LogRecord record) { if (record == null) { throw new NullPointerException(); } final Method m = ZDT_OF_INSTANT; if (m != null) { try { return (Comparable<?>) m.invoke((Object) null, LR_GET_INSTANT.invoke...
@Test @SuppressWarnings("unchecked") public void testGetZonedDateTime() throws Exception { LogRecord r1 = new LogRecord(Level.SEVERE, ""); LogRecord r2 = new LogRecord(Level.SEVERE, ""); try { final Class<?> k = Class.forName("java.time.ZonedDateTime"); setEpochSecond(r1, 100, 1); setEpochSecond(r2, 100, 1); Comparable...
MailHandler extends Handler { @Override public boolean isLoggable(final LogRecord record) { int levelValue = getLevel().intValue(); if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return false; } Filter body = getFilter(); if (body == null || body.isLoggable(record)) { setMatchedPart(-1); ret...
@Test public void testIsLoggable() { final Level[] lvls = getAllLevels(); if (lvls.length > 0) { LogRecord record = new LogRecord(Level.INFO, ""); for (Level lvl : lvls) { testLoggable(lvl, null); testLoggable(lvl, record); } } else { fail("No predefined levels."); } }
MailHandler extends Handler { public void postConstruct() { } MailHandler(); MailHandler(final int capacity); MailHandler(final Properties props); @Override boolean isLoggable(final LogRecord record); @Override void publish(final LogRecord record); void postConstruct(); void preDestroy(); void push(); @Override void ...
@Test public void testPostConstruct() { MailHandler instance = new MailHandler(createInitProperties("")); InternalErrorManager em = new InternalErrorManager(); instance.setErrorManager(em); instance.postConstruct(); assertEquals(true, em.exceptions.isEmpty()); instance.close(); }
MailHandler extends Handler { public void preDestroy() { push(false, ErrorManager.CLOSE_FAILURE); } MailHandler(); MailHandler(final int capacity); MailHandler(final Properties props); @Override boolean isLoggable(final LogRecord record); @Override void publish(final LogRecord record); void postConstruct(); void preD...
@Test public void testPreDestroy() { MailHandler instance = new MailHandler(createInitProperties("")); InternalErrorManager em = new InternalErrorManager(); instance.setErrorManager(em); instance.preDestroy(); assertEquals(true, em.exceptions.isEmpty()); instance.close(); instance = createHandlerWithRecords(); em = int...
MailHandler extends Handler { @Override public void publish(final LogRecord record) { if (tryMutex()) { try { if (isLoggable(record)) { record.getSourceMethodName(); publish0(record); } } catch (final LinkageError JDK8152515) { reportLinkageError(JDK8152515, ErrorManager.WRITE_FAILURE); } finally { releaseMutex(); } } ...
@Test public void testPublish() { MailHandler instance = createHandlerWithRecords(); InternalErrorManager em = internalErrorManagerFrom(instance); assertEquals(em.exceptions.isEmpty(), true); instance.close(); assertEquals(true, em.exceptions.get(0) instanceof MessagingException); assertEquals(1, em.exceptions.size());...
MailHandler extends Handler { private void reset() { assert Thread.holdsLock(this); if (size < data.length) { Arrays.fill(data, 0, size, null); } else { Arrays.fill(data, null); } this.size = 0; } MailHandler(); MailHandler(final int capacity); MailHandler(final Properties props); @Override boolean isLoggable(final L...
@Test public void testAlignEmptyFilter() throws Exception { String p = MailHandler.class.getName(); Properties props = createInitProperties(p); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName()); props.put(p.concat(".attachment.names"), "att.txt"); final LogManager manager = LogManager.getLo...
PropUtil { public static boolean getBooleanProperty(Properties props, String name, boolean def) { return getBoolean(getProp(props, name), def); } private PropUtil(); static int getIntProperty(Properties props, String name, int def); static boolean getBooleanProperty(Properties props, String name, boolean def); @De...
@Test public void testBool() throws Exception { Properties props = new Properties(); props.setProperty("test", "true"); assertTrue(PropUtil.getBooleanProperty(props, "test", false)); } @Test public void testBoolDef() throws Exception { Properties props = new Properties(); assertTrue(PropUtil.getBooleanProperty(props, "...
MailHandler extends Handler { public void push() { push(true, ErrorManager.FLUSH_FAILURE); } MailHandler(); MailHandler(final int capacity); MailHandler(final Properties props); @Override boolean isLoggable(final LogRecord record); @Override void publish(final LogRecord record); void postConstruct(); void preDestroy(...
@Test public void testPush() { MailHandler instance = new MailHandler(createInitProperties("")); InternalErrorManager em = new InternalErrorManager(); instance.setErrorManager(em); instance.push(); assertEquals(true, em.exceptions.isEmpty()); instance.close(); instance = createHandlerWithRecords(); em = internalErrorMa...
MailHandler extends Handler { @Override public void flush() { push(false, ErrorManager.FLUSH_FAILURE); } MailHandler(); MailHandler(final int capacity); MailHandler(final Properties props); @Override boolean isLoggable(final LogRecord record); @Override void publish(final LogRecord record); void postConstruct(); void...
@Test public void testFlush() { MailHandler instance = new MailHandler(createInitProperties("")); InternalErrorManager em = new InternalErrorManager(); instance.setErrorManager(em); instance.flush(); assertEquals(true, em.exceptions.isEmpty()); instance.close(); instance = createHandlerWithRecords(); em = internalError...
MailHandler extends Handler { @Override public void close() { try { checkAccess(); Message msg = null; synchronized (this) { try { msg = writeLogRecords(ErrorManager.CLOSE_FAILURE); } finally { this.logLevel = Level.OFF; if (this.capacity > 0) { this.capacity = -this.capacity; } if (size == 0 && data.length != 1) { thi...
@Test public void testClose() { LogRecord record = new LogRecord(Level.INFO, ""); MailHandler instance = new MailHandler(createInitProperties("")); InternalErrorManager em = new InternalErrorManager(); instance.setErrorManager(em); int capacity = instance.getCapacity(); assertNotNull(instance.getLevel()); instance.setL...
MailHandler extends Handler { final String contentTypeOf(CharSequence chunk) { if (!isEmpty(chunk)) { final int MAX_CHARS = 25; if (chunk.length() > MAX_CHARS) { chunk = chunk.subSequence(0, MAX_CHARS); } try { final String charset = getEncodingName(); final byte[] b = chunk.toString().getBytes(charset); final ByteArra...
@Test public void testContentTypeOf() throws IOException { MailHandler instance = new MailHandler(createInitProperties("")); InternalErrorManager em = new InternalErrorManager(); instance.setErrorManager(em); instance.setEncoding((String) null); String head = instance.contentTypeOf(new XMLFormatter().getHead(instance))...
MailHandler extends Handler { @Override protected void reportError(String msg, Exception ex, int code) { try { if (msg != null) { errorManager.error(Level.SEVERE.getName() .concat(": ").concat(msg), ex, code); } else { errorManager.error(null, ex, code); } } catch (RuntimeException | LinkageError GLASSFISH_21258) { rep...
@Test public void testReportError() { MailHandler instance = new MailHandler(createInitProperties("")); instance.setErrorManager(new ErrorManager() { @Override public void error(String msg, Exception ex, int code) { assertNull(msg); } }); instance.reportError(null, null, ErrorManager.GENERIC_FAILURE); instance.setError...
MailHandler extends Handler { @SuppressWarnings({"UseSpecificCatch", "ThrowableResultIgnored"}) final boolean isMissingContent(Message msg, Throwable t) { final Object ccl = getAndSetContextClassLoader(MAILHANDLER_LOADER); try { msg.writeTo(new ByteArrayOutputStream(MIN_HEADER_SIZE)); } catch (final RuntimeException RE...
@Test public void testIsMissingContent() throws Exception { Properties props = createInitProperties(""); MailHandler target = new MailHandler(props); Session session = Session.getInstance(props); MimeMessage msg = new MimeMessage(session); Address[] from = InternetAddress.parse("me@localhost", false); msg.addFrom(from)...
MailHandler extends Handler { private void intern() { assert Thread.holdsLock(this); try { Object canidate; Object result; final Map<Object, Object> seen = new HashMap<>(); try { intern(seen, this.errorManager); } catch (final SecurityException se) { reportError(se.getMessage(), se, ErrorManager.OPEN_FAILURE); } try { ...
@Test public void testIntern() throws Exception { assertNull(System.getSecurityManager()); final String p = MailHandler.class.getName(); Properties props = createInitProperties(p); props.put(p.concat(".errorManager"), InternFilterErrorManager.class.getName()); props.put(p.concat(".comparator"), InternFilterFormatterCom...
MailHandler extends Handler { private static void verifyProperties(Session session, String protocol) { session.getProperty("mail.from"); session.getProperty("mail." + protocol + ".from"); session.getProperty("mail.dsn.ret"); session.getProperty("mail." + protocol + ".dsn.ret"); session.getProperty("mail.dsn.notify"); s...
@Test public void testVerifyProperties() throws Exception { Properties props = createInitProperties(""); props.put("subject", "test"); props.put("verify", "limited"); InternalErrorManager em = new InternalErrorManager(); MailHandler instance = new MailHandler(); try { instance.setErrorManager(em); instance.setMailPrope...
MailHandler extends Handler { private void initSubject(final String p) { assert Thread.holdsLock(this); String name = fromLogManager(p.concat(".subject")); if (name == null) { name = "com.sun.mail.util.logging.CollectorFormatter"; } if (hasValue(name)) { try { this.subjectFormatter = LogManagerProperties.newFormatter(n...
@Test public void testInitSubject() throws Exception { InternalErrorManager em; MailHandler target; final String p = MailHandler.class.getName(); final LogManager manager = LogManager.getLogManager(); Properties props = createInitProperties(p); props.put(p.concat(".errorManager"), InternalErrorManager.class.getName());...
MailHandler extends Handler { private void initAuthenticator(final String p) { assert Thread.holdsLock(this); String name = fromLogManager(p.concat(".authenticator")); if (name != null && !"null".equalsIgnoreCase(name)) { if (name.length() != 0) { try { this.auth = LogManagerProperties .newObjectFrom(name, Authenticato...
@Test public void testInitAuthenticator() throws Exception { testInitAuthenticator("user", null); testInitAuthenticator("user", "null"); testInitAuthenticator("user", "NULL"); testInitAuthenticator("user", "Null"); testInitAuthenticator("user", ""); testInitAuthenticator("user", "somepassword"); }
MailHandler extends Handler { private void initAttachmentFilters(final String p) { assert Thread.holdsLock(this); assert this.attachmentFormatters != null; final String list = fromLogManager(p.concat(".attachment.filters")); if (!isEmpty(list)) { final String[] names = list.split(","); Filter[] a = new Filter[names.len...
@Test public void testInitAttachmentFilters() throws Exception { InternalErrorManager em; MailHandler target; final String p = MailHandler.class.getName(); final LogManager manager = LogManager.getLogManager(); final Properties props = createInitProperties(p); props.put(p.concat(".errorManager"), InternalErrorManager.c...
MailHandler extends Handler { private void initAttachmentNames(final String p) { assert Thread.holdsLock(this); assert this.attachmentFormatters != null; final String list = fromLogManager(p.concat(".attachment.names")); if (!isEmpty(list)) { final String[] names = list.split(","); final Formatter[] a = new Formatter[n...
@Test public void testInitAttachmentNames() throws Exception { InternalErrorManager em; MailHandler target; final String p = MailHandler.class.getName(); final LogManager manager = LogManager.getLogManager(); Properties props = createInitProperties(p); props.put(p.concat(".errorManager"), InternalErrorManager.class.get...
SeverityComparator implements Comparator<LogRecord>, Serializable { public Throwable apply(final Throwable chain) { int limit = 0; Throwable root = chain; Throwable high = null; Throwable normal = null; for (Throwable cause = chain; cause != null; cause = cause.getCause()) { root = cause; if (isNormal(cause)) { normal ...
@Test public void testApplyNull() { SeverityComparator a = new SeverityComparator(); assertNull(a.apply(null)); } @Test public void testApplyErrorByNormal() { SeverityComparator a = new SeverityComparator(); Throwable next = this.headIeChain(new AssertionError()); next = new Error(next); next = new NoClassDefFoundError...
SeverityComparator implements Comparator<LogRecord>, Serializable { public int compareThrowable(final Throwable t1, final Throwable t2) { if (t1 == t2) { return 0; } else { if (t1 == null) { return isNormal(t2) ? 1 : -1; } else { if (t2 == null) { return isNormal(t1) ? -1 : 1; } } if (t1.getClass() == t2.getClass()) { ...
@Test public void testCompareThrownDoesNotApply() { SeverityComparator a = new SeverityComparator(); Throwable tc1 = new Error(new Exception()); Throwable tc2 = new Exception(new Exception()); assertTrue(a.compareThrowable(tc1, tc2) > 0); assertTrue(a.compareThrowable(tc2, tc1) < 0); tc1 = new RuntimeException(tc1); as...
SeverityComparator implements Comparator<LogRecord>, Serializable { public final int applyThenCompare(Throwable tc1, Throwable tc2) { return tc1 == tc2 ? 0 : compareThrowable(apply(tc1), apply(tc2)); } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowabl...
@Test public void testApplyThenCompareNull() { SeverityComparator a = new SeverityComparator(); assertEquals(0, a.applyThenCompare((Throwable) null, (Throwable) null)); }
SeverityComparator implements Comparator<LogRecord>, Serializable { static SeverityComparator getInstance() { return (SeverityComparator) INSTANCE; } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @Suppress...
@Test public void testGetInstance() { SeverityComparator a = new SeverityComparator(); assertEquals(a, SeverityComparator.getInstance()); assertEquals(a.getClass(), SeverityComparator.getInstance().getClass()); assertEquals(a.hashCode(), SeverityComparator.getInstance().hashCode()); }
SeverityComparator implements Comparator<LogRecord>, Serializable { public boolean isNormal(final Throwable t) { if (t == null) { return false; } final Class<?> root = Throwable.class; final Class<?> error = Error.class; for (Class<?> c = t.getClass(); c != root; c = c.getSuperclass()) { if (error.isAssignableFrom(c)) ...
@Test public void testIsNormal() { SeverityComparator a = new SeverityComparator(); assertTrue(a.isNormal(this.headIeChain(null))); assertTrue(a.isNormal(this.headIioeChain(null))); assertTrue(a.isNormal(this.headCbieChain(null))); assertTrue(a.isNormal(this.headFlieChain(null))); assertTrue(a.isNormal(this.headSubIeCh...
SeverityComparator implements Comparator<LogRecord>, Serializable { @SuppressWarnings("override") public int compare(final LogRecord o1, final LogRecord o2) { if (o1 == null || o2 == null) { throw new NullPointerException(toString(o1, o2)); } if (o1 == o2) { return 0; } int cmp = compare(o1.getLevel(), o2.getLevel()); ...
@Test(expected = NullPointerException.class) public void testCompareNullAndNull() { SeverityComparator a = new SeverityComparator(); a.compare((LogRecord) null, (LogRecord) null); }
CompositeBuffer implements Buffer { public static CompositeBuffer newBuffer() { return BuffersBuffer.create(); } static CompositeBuffer newBuffer(); static CompositeBuffer newBuffer(final MemoryManager memoryManager); static CompositeBuffer newBuffer(final MemoryManager memoryManager, final Buffer... buffe...
@Test public void testSplitWithMark() { final CompositeBuffer composite = CompositeBuffer.newBuffer( mm, Buffers.wrap(mm, "hello"), Buffers.wrap(mm, " world")); composite.position(4); composite.mark(); Buffer otherHalf = composite.split(6); assertMarkExceptionThrown(otherHalf); composite.reset(); otherHalf = composite....
MimeHeaders { public Iterable<String> names() { return namesIterable; } MimeHeaders(); void mark(); void recycle(); void clear(); @Override String toString(); void copyFrom(final MimeHeaders source); int size(); int trailerSize(); DataChunk getName(int n); DataChunk getValue(int n); boolean isSerialized(int n); boolean...
@Test public void testNames() throws Exception { final String[] expectedNames = { "custom-before", "custom-before-2", "custom-after", "custom-after-2" }; Iterable<String> result = mimeHeaders.names(); List<String> list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedNames,...
MimeHeaders { public Iterable<String> trailerNames() { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new NamesIterator(MimeHeaders.this, true); } }; } MimeHeaders(); void mark(); void recycle(); void clear(); @Override String toString(); void copyFrom(final MimeHeaders source); i...
@Test public void testTrailerNames() throws Exception { final String[] expectedNames = { "custom-after", "custom-after-2" }; Iterable<String> result = mimeHeaders.trailerNames(); List<String> list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedNames, list.toArray(new Stri...
MimeHeaders { public Iterable<String> values(final String name) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new ValuesIterator(MimeHeaders.this, name, false); } }; } MimeHeaders(); void mark(); void recycle(); void clear(); @Override String toString(); void copyFrom(final Mim...
@Test public void testValues() throws Exception { final String[] expectedValuesSet1 = { "one", "two", "three" }; final String[] expectedValuesSet2 = { "one" }; Iterable<String> result = mimeHeaders.values("custom-before"); List<String> list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArra...
MimeHeaders { public Iterable<String> trailerValues(final String name) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new ValuesIterator(MimeHeaders.this, name, true); } }; } MimeHeaders(); void mark(); void recycle(); void clear(); @Override String toString(); void copyFrom(fin...
@Test public void testTrailerValues() throws Exception { final String[] expectedValuesSet1 = { "one", "two", "three" }; final String[] expectedValuesSet2 = { "one" }; final String[] emptySet = {}; Iterable<String> result = mimeHeaders.trailerValues("custom-before"); List<String> list = new ArrayList<>(); for (String s ...
ApacheLogFormat implements AccessLogFormat { String unsafeFormat(Response response, Date timeStamp, long responseNanos) { final StringBuilder builder = new StringBuilder(); final Request request = response.getRequest(); for (Field field: fields) { field.format(builder, request, response, timeStamp, responseNanos); } re...
@Test public void testBasicFormats() { final Response response = mockSimpleResponse(); Locale.setDefault(Locale.US); assertEquals("remote-host - remote-user [2014/Jan/15:23:45:12 +0000] \"GET /test/path?testing=true HTTP/1.1\" 210 1234567", ApacheLogFormat.COMMON_UTC.unsafeFormat(response, date, nanos)); assertEquals("...
ApacheLogFormat implements AccessLogFormat { public String getFormat() { final StringBuilder builder = new StringBuilder(); for (Field field: fields) builder.append(field.toString()); return builder.toString(); } ApacheLogFormat(String format); ApacheLogFormat(TimeZone timeZone, String format); @Override String format...
@Test public void testGetFormat() { assertFormat("%a"); assertFormat("%A"); assertFormat("%b"); assertFormat("%B"); assertFormat("%{Test-Cookie}C", "%{test-cookie}C"); assertFormat("%D"); assertFormat("%h"); assertFormat("%{remote}h", "%h"); assertFormat("%{local}h"); assertFormat("%H"); assertFormat("%{User-Agent}i", ...
CompressionEncodingFilter implements EncodingFilter { @Override public boolean applyEncoding(final HttpHeader httpPacket) { if (httpPacket.isRequest()) { assert httpPacket instanceof HttpRequestPacket; return false; } assert httpPacket instanceof HttpResponsePacket; return canCompressHttpResponse((HttpResponsePacket) h...
@Test public void testAcceptEncodingProcessing() throws Exception { final CompressionEncodingFilter filter = new CompressionEncodingFilter(CompressionMode.ON, 1, new String[0], new String[0], new String[] {"gzip"}); HttpRequestPacket request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(P...
CompressionEncodingFilter implements EncodingFilter { @Override public boolean applyDecoding(final HttpHeader httpPacket) { if(! httpPacket.isRequest()) { return false; } assert httpPacket instanceof HttpRequestPacket; return canDecompressHttpRequest((HttpRequestPacket) httpPacket, compressionConfig, aliases); } Compre...
@Test public void testContentEncodingProcessing() throws Exception { final CompressionEncodingFilter filter = new CompressionEncodingFilter(CompressionMode.ON, 1, new String[0], new String[0], new String[] {"gzip"}, true); HttpRequestPacket request = setContentEncoding( HttpRequestPacket.builder().method(Method.GET).pr...
CompositeBuffer implements Buffer { public abstract int bulk(BulkOperation operation); static CompositeBuffer newBuffer(); static CompositeBuffer newBuffer(final MemoryManager memoryManager); static CompositeBuffer newBuffer(final MemoryManager memoryManager, final Buffer... buffers); static CompositeBuffe...
@Test public void testBulk() { final Charset ascii = Charset.forName("ASCII"); final CompositeBuffer composite = CompositeBuffer.newBuffer( mm, Buffers.wrap(mm, "hello", ascii), Buffers.wrap(mm, " world", ascii)); composite.bulk(new CompositeBuffer.BulkOperation() { @Override public boolean processByte(byte value, fina...
PooledMemoryManager implements MemoryManager<Buffer>, WrapperAware { Pool[] getPools() { return Arrays.copyOf(pools, pools.length); } PooledMemoryManager(); @SuppressWarnings("unused") PooledMemoryManager(final boolean isDirect); PooledMemoryManager( final int baseBufferSize, final int numberO...
@Test public void testDefaultPoolInitialization() throws Exception { final int numProcessors = Runtime.getRuntime().availableProcessors(); final long maxMemory = Runtime.getRuntime().maxMemory(); final long totalMemory = (long) (maxMemory * DEFAULT_HEAP_USAGE_PERCENTAGE); final long upperBound = (long) (maxMemory * .10...
PooledMemoryManager implements MemoryManager<Buffer>, WrapperAware { @Override public Buffer reallocate(final Buffer oldBuffer, final int newSize) { if (newSize == 0) { oldBuffer.tryDispose(); return Buffers.EMPTY_BUFFER; } final int curBufSize = oldBuffer.capacity(); if (oldBuffer instanceof PoolBuffer) { if (curBufSi...
@Test public void testReallocate() throws Exception { PooledMemoryManager mm = new PooledMemoryManager(DEFAULT_BASE_BUFFER_SIZE, 1, 0, 1, DEFAULT_HEAP_USAGE_PERCENTAGE, DEFAULT_PREALLOCATED_BUFFERS_PERCENTAGE, isDirect); Buffer b = mm.allocate(2048); Buffer nb = mm.reallocate(b, 1024); assertEquals(1024, nb.limit()); a...
FileTransfer implements WritableMessage { @Override public int remaining() { return ((len > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) len); } FileTransfer(final File f); FileTransfer(final File f, final long pos, final long len); long writeTo(final WritableByteChannel c); @Override boolean hasRemaining(); @Overri...
@Test public void testSimpleFileTransfer() throws Exception { TCPNIOTransport t = TCPNIOTransportBuilder.newInstance().build(); FilterChainBuilder builder = FilterChainBuilder.stateless(); final File f = generateTempFile(1024 * 1024); builder.add(new TransportFilter()); builder.add(new BaseFilter() { @Override public N...
AbstractSupplier implements Observer, Supplier<T> { @Override public void onResume() { this.logger().log(Level.INFO, "On Resume"); dataManager().addObserver(this); this.logger().log(Level.INFO, "Syncstatus: " + this.dataManager().getSyncStatus()); switch (dataManager().getSyncStatus()) { case NOT_SYNCED: this.dataManag...
@Test public void teste_onResume_withSyncedDataManager_shouldNotCallSync() { StubbedDataManager dataManager = new StubbedDataManager(); dataManager.setStatus(SyncStatus.SYNCED); FullfilledSupplier componenet_under_test = new FullfilledSupplier(dataManager); componenet_under_test.onResume(); assertThat(dataManager.syncC...
OneDayFilter implements Filter<Transaction> { @Override public boolean shouldBeRemoved(Transaction t) { return getZeroTimeDate(t.booking().getDate()).compareTo(this.day) != 0; } OneDayFilter(Date day); @Override boolean shouldBeRemoved(Transaction t); }
@Test public void teste_filter_withNotMatchingDay_shouldReturnLeave() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date expectedDate = sdf.parse("11/07/2017"); Date bookingDate = sdf.parse("12/07/2017"); Booking booking = new Booking(); booking.setDate(bookingDate); Transaction testTran...
ItemCheckedMap implements Filter<Transaction> { public boolean hasItemsChecked() { Boolean ret = false; Iterator iterator = this.map.entrySet().iterator(); while (iterator.hasNext() && !ret) { Map.Entry entry = (Map.Entry) iterator.next(); ret = (Boolean) entry.getValue(); } return ret; } ItemCheckedMap(HashMap<String,...
@Test public void teste_hasItemsChecked_withEmptyMap_shouldReturnFalse() { ItemCheckedMap component_under_test = new ItemCheckedMap(new HashMap<String, Boolean>()); assertThat(component_under_test.hasItemsChecked()).isFalse(); } @Test public void teste_hasItemsChecked_withFilledMapAndNothingChecked_shouldReturnFalse() ...
ItemCheckedMap implements Filter<Transaction> { public boolean shouldBePresented(String bankAccountID) { return this.map.containsKey(bankAccountID) && this.map.get(bankAccountID).booleanValue(); } ItemCheckedMap(HashMap<String, Boolean> map); boolean hasItemsChecked(); boolean shouldBePresented(String bankAccountID); v...
@Test public void teste_shouldBePresented_withNoKeyInMap_shouldReturnFalse() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test2", true); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.shouldBePresented("test1")).isFalse(); } @Test public void teste_should...
ItemCheckedMap implements Filter<Transaction> { @Override public boolean shouldBeRemoved(Transaction t) { if (this.map.isEmpty()) { return false; } boolean shouldStay = shouldBePresented(t.bankAccountID()); return !shouldStay; } ItemCheckedMap(HashMap<String, Boolean> map); boolean hasItemsChecked(); boolean shouldBePr...
@Test public void teste_shouldBeRemoved_withWithKeyInMapAndValueTrue_shouldReturnFalse() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test1", true); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.shouldBeRemoved(new Transaction(null, "test1", null))).isFa...
AbstractSupplier implements Observer, Supplier<T> { @Override public void addDataListeningObject(DataListening observer) { if (this.dataListenings.isEmpty()) { this.dataManager().addObserver(this); } this.dataListenings.add(observer); } @Override List<T> getAll(); @Override void onResume(); @Override void addDataListe...
@Test public void teste_addDataListening_shouldRegisterItselfOnDataManager() { StubbedDataManager dataManager = new StubbedDataManager(); FullfilledSupplier componenet_under_test = new FullfilledSupplier(dataManager); DummyDataListening dataListening = new DummyDataListening(); componenet_under_test.addDataListeningObj...
BankingDateInformation { public double getAmountDelta() { double amountDelta = 0.0; for (Transaction transaction : this.transactionSupplier.getAll()) { amountDelta += transaction.booking().getAmount(); } return amountDelta; } BankingDateInformation(double amount, Supplier<Transaction> transactionSupplier); double getAm...
@Test public void getAmountDelta_noBookings() { double amount = 123.456; BankingDateInformation bankingDateInformation = new BankingDateInformation(amount, new StubbedBankTransactionSupplier()); assertThat(bankingDateInformation.getAmountDelta()).isZero(); } @Test public void getAmountDelta_bookings() { double amount =...
SavingsComparator implements Comparator<SavingsAccount> { @Override public int compare(SavingsAccount t1, SavingsAccount t2) { return t1.getFinaldate().compareTo(t2.getFinaldate()); } @Override int compare(SavingsAccount t1, SavingsAccount t2); }
@Test public void teste_compare_withEqualSavings_shouldReturnZero() { SavingsComparator component_under_test = new SavingsComparator(); SavingsAccount account = new SavingsAccount(123, "some anme", 10, 0, any(), any()); assertThat(component_under_test.compare(account, account)).isEqualTo(0); } @Test public void teste_c...
BankingApiFacade { public List<BankAccessBankingModel> getBankAccesses(final String userId) throws BankingException { return binder.getBankAccessEndpoint(userId).getBankAccesses(); } @Autowired BankingApiFacade(final BankingApiBinder binder); protected BankingApiFacade(); List<BankAccessBankingModel> getBankAccesses(...
@Test public void getAccessesBinderCalled() { DummyBankAccessEndpoint endpoint = mock(DummyBankAccessEndpoint.class); when(bankingApiBinder.getBankAccessEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.getBankAccesses("test")...
BankingApiFacade { public List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId) throws BankingException { return binder.getBankAccountEndpoint(userId).getBankAccounts(bankAccessId); } @Autowired BankingApiFacade(final BankingApiBinder binder); protected BankingApiFacade(); List...
@Test public void getAccountsBinderCalled() { DummyBankAccountEndpoint endpoint = mock(DummyBankAccountEndpoint.class); when(bankingApiBinder.getBankAccountEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.getBankAccounts("tes...
BankingApiFacade { public List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin) throws BankingException { return binder.getBankAccountEndpoint(userId).syncBankAccount(bankAccessId, bankAccountId, pin); } @Autowired BankingApiFacade(final Bankin...
@Test public void syncAccountBinderCalled() { DummyBankAccountEndpoint endpoint = mock(DummyBankAccountEndpoint.class); when(bankingApiBinder.getBankAccountEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.syncBankAccount("tes...
DummyBankAccountEndpoint implements BankAccountEndpoint { @Override public List<BankAccountBankingModel> getBankAccounts(String bankingAccessId) throws BankingException { if (!dummyBankAccessEndpoint.existsBankAccess(bankingAccessId)) { return new ArrayList<BankAccountBankingModel>(); } if (!bankAccountBankingModelRepo...
@Test public void getBankAccountsAccountsExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); Dum...
AbstractDataManager extends Observable implements DataManager<T> { @Override public SyncStatus getSyncStatus() { return syncStatus; } AbstractDataManager(DataProvider<T> dataProvider); @Override void sync(); @Override SyncStatus getSyncStatus(); @Override List<T> getAll(); @Override void add(final T element, final Serv...
@Test public void test_initialState_isNotInSync(){ FullfilledDataManager component_under_test = new FullfilledDataManager(new StubbedSavingsProvider()); assertThat(component_under_test.getSyncStatus()).isEqualTo(SyncStatus.NOT_SYNCED); }
DummyBankAccountEndpoint implements BankAccountEndpoint { @Override public List<BookingModel> syncBankAccount(String bankAccessId, String bankAccountId, String pin) throws BankingException { if (!bookingModelMap.containsKey(bankAccountId)) { generateDummyBookingModels(bankAccountId); updateAccountBalance(bankAccountId)...
@Test public void syncBankAccountsAccountsNotExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class);...
BankingApiBinder { BankAccountEndpoint getBankAccountEndpoint(final String userId) { return isTestUser(userId) ? dummyBankAccountEndpoint : httpBankAccountEndpoint; } @Autowired BankingApiBinder(final BankingApiConfiguration bankingApiConfiguration, @Qualifier("default") final BankAccessEnd...
@Test public void getBankAccountEndpointDummy() { String username = "test@user.de"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, null, null, new HttpBankAccountEndpoint(null, null), new DummyBankAccountEndpoint(null, null, null)); BankAccountEndpoint endpoint = bankingApiBinder...
BankingApiBinder { BankAccessEndpoint getBankAccessEndpoint(final String userId) { return isTestUser(userId) ? dummyBankAccessEndpoint : httpBankAccessEndpoint; } @Autowired BankingApiBinder(final BankingApiConfiguration bankingApiConfiguration, @Qualifier("default") final BankAccessEndpoin...
@Test public void getBankAccessEndpointDummy() { String username = "test@user.de"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, new HttpBankAccessEndpoint(null, null), new DummyBankAccessEndpoint(), null, null); BankAccessEndpoint endpoint = bankingApiBinder.getBankAccessEndpoi...
DummyBankAccessEndpoint implements BankAccessEndpoint { @Override public BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess) throws BankingException { BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setId("TestID" + number + "_" + System.nanoTime(...
@Test public void addRepositoryCalled() throws Exception { String testUser = "user"; String testBankCode = "testCode"; String testBankLogin = "testLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setUserId(testUser); bankAccessBankingModel.setBankLogin(testBan...
DummyBankAccessEndpoint implements BankAccessEndpoint { public boolean existsBankAccess(String bankAccessId) { return bankAccessEndpointRepository.exists(bankAccessId); } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBanking...
@Test public void existsRepositoryCalled() throws Exception { String testId = "test"; DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpointRepository.exists(anyString())).thenReturn(true); DummyBankAccessEndpoint dummyBankAccess...
DummyBankAccessEndpoint implements BankAccessEndpoint { @Override public List<BankAccessBankingModel> getBankAccesses() throws BankingException { List<DummyBankAccessBankingModelEntity> dummyBankAccessBankingModelEntities = bankAccessEndpointRepository.findAll(); List<BankAccessBankingModel> bankAccessBankingModelList ...
@Test public void getRepositoryCalled() throws Exception { String testId = "test"; DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpointRepository.findAll()).thenReturn(new ArrayList<DummyBankAccessBankingModelEntity>()); DummyB...
UserRegistrationFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String email = keycloakUtilizer.getEmail(); String firstName = keycloakUtilizer.getFirstName(); String lastName = keycloakUtilizer...
@Test(expected = ServletException.class) public void filterEmailNull() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer(null, "first", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletRespon...
AbstractDataManager extends Observable implements DataManager<T> { @Override public void add(final T element, final ServerCallStatusHandler handler) { logger().info("Adding element: " + element); Consumer<StringApiModel> onNext = new Consumer<StringApiModel>() { @Override public void accept(@NonNull final StringApiMode...
@Test public void test_add_shouldAddItemOnDataProvider() throws Exception{ StubbedSavingsProvider dataProvider = new StubbedSavingsProvider(); FullfilledDataManager component_under_test = new FullfilledDataManager(dataProvider); SavingsAccount savingsAccount = new SavingsAccount(); component_under_test.add(savingsAccou...
AuthenticationController { public String register(User user) throws VirtualLedgerAuthenticationException, UserAlreadyExistsException { if (user == null || user.getEmail() == null || user.getFirstName() == null || user.getLastName() == null) { throw new VirtualLedgerAuthenticationException( "Please check your inserts! A...
@Test(expected = UserAlreadyExistsException.class) public void testRegisterWithExistingUserShouldThrowException() throws Exception { UserRepository userRepositoryMock = mock(UserRepository.class); when(userRepositoryMock.existsUserWithEmail(someEmail())).thenReturn(Boolean.TRUE); AuthenticationController componentUnder...
StringApiModelFactory { public StringApiModel createStringApiModel(String string) { StringApiModel stringApiModel = new StringApiModel(); stringApiModel.setData(string); return stringApiModel; } StringApiModel createStringApiModel(String string); }
@Test public void createSuccessful() { String testString = "test"; StringApiModel stringApiModel = stringApiModelFactory.createStringApiModel(testString); Assert.assertNotNull(stringApiModel); Assert.assertEquals(testString, stringApiModel.getData()); }
AbstractDataManager extends Observable implements DataManager<T> { @Override public List<T> getAll() throws SyncFailedException { if (syncFailedException != null) throw syncFailedException; if (syncStatus != SYNCED) throw new IllegalStateException("Sync not completed"); logger().info("Number items synct: " + this.allCa...
@Test(expected = IllegalStateException.class) public void test_initialState_get_shouldThrowIllegalArgumentException() throws Exception{ FullfilledDataManager component_under_test = new FullfilledDataManager(new StubbedSavingsProvider()); component_under_test.getAll(); }
BankAccessFactory { public BankAccess createBankAccess(BankAccessBankingModel bankingModel) { BankAccess bankAccess = new BankAccess(bankingModel.getId(), bankingModel.getBankName(), bankingModel.getBankCode(), bankingModel.getBankLogin()); return bankAccess; } BankAccess createBankAccess(BankAccessBankingModel bankin...
@Test public void createSuccess() { String accessId = "accessID"; String bankName = "bankName"; String bankCode = "bankCode"; String bankLogin = "bankLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setBankName(bankName); bankAccessBankingModel.setBankCode(ban...