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; } Protocol(String host, int port,
Properties props, String prefix,
boolean isSSL, MailLogger logger); Protocol(InputStream in, PrintStream out, Properties props,
boolean debug); long getTimestamp(); void addResponseHandler(ResponseHandler h); void removeResponseHandler(ResponseHandler h); void notifyResponseHandlers(Response[] responses); Response readResponse(); boolean hasResponse(); String writeCommand(String command, Argument args); synchronized Response[] command(String command, Argument args); void handleResult(Response response); void simpleCommand(String cmd, Argument args); synchronized void startTLS(String cmd); synchronized void startCompression(String cmd); boolean isSSL(); InetAddress getInetAddress(); SocketChannel getChannel(); boolean supportsUtf8(); } | @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, nullps, props, false); tag = p.writeCommand("CMD", null); assertEquals("A0", tag); } |
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 props, boolean debug); FetchItem[] getFetchItems(); void capability(); void handleCapabilityResponse(Response[] r); boolean isAuthenticated(); boolean isREV1(); @Override Response readResponse(); boolean hasCapability(String c); Map<String, String> getCapabilities(); boolean supportsUtf8(); @Override void disconnect(); void noop(); void logout(); void login(String u, String p); synchronized void authlogin(String u, String p); synchronized void authplain(String authzid, String u, String p); synchronized void authntlm(String authzid, String u, String p); synchronized void authoauth2(String u, String p); void sasllogin(String[] allowed, String realm, String authzid,
String u, String p); void proxyauth(String u); String getProxyAuthUser(); void unauthenticate(); @Deprecated void id(String guid); void startTLS(); void compress(); MailboxInfo select(String mbox); MailboxInfo select(String mbox, ResyncData rd); MailboxInfo examine(String mbox); MailboxInfo examine(String mbox, ResyncData rd); void enable(String cap); boolean isEnabled(String cap); void unselect(); Status status(String mbox, String[] items); void create(String mbox); void delete(String mbox); void rename(String o, String n); void subscribe(String mbox); void unsubscribe(String mbox); ListInfo[] list(String ref, String pattern); ListInfo[] lsub(String ref, String pattern); void append(String mbox, Flags f, Date d,
Literal data); AppendUID appenduid(String mbox, Flags f, Date d,
Literal data); AppendUID appenduid(String mbox, Flags f, Date d,
Literal data, boolean uid); void check(); void close(); void expunge(); void uidexpunge(UIDSet[] set); BODYSTRUCTURE fetchBodyStructure(int msgno); BODY peekBody(int msgno, String section); BODY fetchBody(int msgno, String section); BODY peekBody(int msgno, String section, int start, int size); BODY fetchBody(int msgno, String section, int start, int size); BODY peekBody(int msgno, String section, int start, int size,
ByteArray ba); BODY fetchBody(int msgno, String section, int start, int size,
ByteArray ba); RFC822DATA fetchRFC822(int msgno, String what); Flags fetchFlags(int msgno); UID fetchUID(int msgno); MODSEQ fetchMODSEQ(int msgno); void fetchSequenceNumber(long uid); long[] fetchSequenceNumbers(long start, long end); void fetchSequenceNumbers(long[] uids); int[] uidfetchChangedSince(long start, long end, long modseq); Response[] fetch(MessageSet[] msgsets, String what); Response[] fetch(int start, int end, String what); Response[] fetch(int msg, String what); void copy(MessageSet[] msgsets, String mbox); void copy(int start, int end, String mbox); CopyUID copyuid(MessageSet[] msgsets, String mbox); CopyUID copyuid(int start, int end, String mbox); void move(MessageSet[] msgsets, String mbox); void move(int start, int end, String mbox); CopyUID moveuid(MessageSet[] msgsets, String mbox); CopyUID moveuid(int start, int end, String mbox); void storeFlags(MessageSet[] msgsets, Flags flags, boolean set); void storeFlags(int start, int end, Flags flags, boolean set); void storeFlags(int msg, Flags flags, boolean set); int[] search(MessageSet[] msgsets, SearchTerm term); int[] search(SearchTerm term); int[] sort(SortTerm[] term, SearchTerm sterm); Namespaces namespace(); Quota[] getQuotaRoot(String mbox); Quota[] getQuota(String root); void setQuota(Quota quota); void setACL(String mbox, char modifier, ACL acl); void deleteACL(String mbox, String user); ACL[] getACL(String mbox); Rights[] listRights(String mbox, String user); Rights myRights(String mbox); synchronized void idleStart(); synchronized Response readIdleResponse(); boolean processIdleResponse(Response r); void idleAbort(); Map<String, String> id(Map<String, String> clientParams); } | @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"); assertEquals("section number", "1.1", b.getSection()); String result = new String(b.getByteArray().getNewBytes(), "us-ascii"); assertEquals("getByteArray.getNewBytes", content, result); InputStream is = b.getByteArrayInputStream(); byte[] ba = new byte[is.available()]; is.read(ba); result = new String(ba, "us-ascii"); assertEquals("getByteArrayInputStream", content, result); }
@Test public void testMultipleBodyResponses2() 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", 0, content.length(), null); assertEquals("section number", "1.1", b.getSection()); String result = new String(b.getByteArray().getNewBytes(), "us-ascii"); assertEquals("getByteArray.getNewBytes", content, result); InputStream is = b.getByteArrayInputStream(); byte[] ba = new byte[is.available()]; is.read(ba); result = new String(ba, "us-ascii"); assertEquals("getByteArrayInputStream", content, result); } |
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 session, URLName url); protected IMAPStore(Session session, URLName url,
String name, boolean isSSL); synchronized boolean isSSL(); synchronized void setUsername(String user); synchronized void setPassword(String password); synchronized boolean hasCapability(String capability); void setProxyAuthUser(String user); String getProxyAuthUser(); @Override synchronized boolean isConnected(); @Override synchronized void close(); @Override synchronized Folder getDefaultFolder(); @Override synchronized Folder getFolder(String name); @Override synchronized Folder getFolder(URLName url); @Override Folder[] getPersonalNamespaces(); @Override Folder[] getUserNamespaces(String user); @Override Folder[] getSharedNamespaces(); @Override synchronized Quota[] getQuota(String root); @Override synchronized void setQuota(Quota quota); @Override void handleResponse(Response r); void idle(); synchronized Map<String, String> id(Map<String, String> clientParams); static final int RESPONSE; static final String ID_NAME; static final String ID_VERSION; static final String ID_OS; static final String ID_OS_VERSION; static final String ID_VENDOR; static final String ID_SUPPORT_URL; static final String ID_ADDRESS; static final String ID_DATE; static final String ID_COMMAND; static final String ID_ARGUMENTS; static final String ID_ENVIRONMENT; } | @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 IMAPHandler() { {{ capabilities += " NAMESPACE"; }} @Override public void namespace() throws IOException { untagged("NAMESPACE ((\"\" \"/\")) ((\"~\" \"/\")) " + "((\"" + utf7Folder + "/\" \"/\"))"); ok(); } }); } |
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, URLName url,
String name, boolean isSSL); synchronized boolean isSSL(); synchronized void setUsername(String user); synchronized void setPassword(String password); synchronized boolean hasCapability(String capability); void setProxyAuthUser(String user); String getProxyAuthUser(); @Override synchronized boolean isConnected(); @Override synchronized void close(); @Override synchronized Folder getDefaultFolder(); @Override synchronized Folder getFolder(String name); @Override synchronized Folder getFolder(URLName url); @Override Folder[] getPersonalNamespaces(); @Override Folder[] getUserNamespaces(String user); @Override Folder[] getSharedNamespaces(); @Override synchronized Quota[] getQuota(String root); @Override synchronized void setQuota(Quota quota); @Override void handleResponse(Response r); void idle(); synchronized Map<String, String> id(Map<String, String> clientParams); static final int RESPONSE; static final String ID_NAME; static final String ID_VERSION; static final String ID_OS; static final String ID_OS_VERSION; static final String ID_VENDOR; static final String ID_SUPPORT_URL; static final String ID_ADDRESS; static final String ID_DATE; static final String ID_COMMAND; static final String ID_ARGUMENTS; static final String ID_ENVIRONMENT; } | @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 IMAPUtf8Handler() { @Override public void create(String line) throws IOException { StringTokenizer st = new StringTokenizer(line); st.nextToken(); st.nextToken(); String name = unquote(st.nextToken()); if (name.equals(utf8Folder)) ok(); else no("wrong name"); } @Override public void list(String line) throws IOException { untagged("LIST (\\HasNoChildren) \"/\" \"" + utf8Folder + "\""); ok(); } }); } |
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 IMAPMessage(Session session); synchronized long getModSeq(); @Override Address[] getFrom(); @Override void setFrom(Address address); @Override void addFrom(Address[] addresses); @Override Address getSender(); @Override void setSender(Address address); @Override Address[] getRecipients(Message.RecipientType type); @Override void setRecipients(Message.RecipientType type, Address[] addresses); @Override void addRecipients(Message.RecipientType type, Address[] addresses); @Override Address[] getReplyTo(); @Override void setReplyTo(Address[] addresses); @Override String getSubject(); @Override void setSubject(String subject, String charset); @Override Date getSentDate(); @Override void setSentDate(Date d); @Override Date getReceivedDate(); @Override int getSize(); long getSizeLong(); @Override int getLineCount(); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); String getInReplyTo(); @Override synchronized String getContentType(); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); @Override void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String getDescription(); @Override void setDescription(String description, String charset); @Override String getMessageID(); @Override String getFileName(); @Override void setFileName(String filename); @Override synchronized DataHandler getDataHandler(); @Override void setDataHandler(DataHandler content); @Override InputStream getMimeStream(); @Override void writeTo(OutputStream os); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); @Override synchronized Flags getFlags(); @Override synchronized boolean isSet(Flags.Flag flag); @Override synchronized void setFlags(Flags flag, boolean set); synchronized void setPeek(boolean peek); synchronized boolean getPeek(); synchronized void invalidateHeaders(); synchronized Object getItem(FetchItem fitem); } | @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.cParams != null) filename = bs.cParams.get("name"); return filename; } protected IMAPMessage(IMAPFolder folder, int msgnum); protected IMAPMessage(Session session); synchronized long getModSeq(); @Override Address[] getFrom(); @Override void setFrom(Address address); @Override void addFrom(Address[] addresses); @Override Address getSender(); @Override void setSender(Address address); @Override Address[] getRecipients(Message.RecipientType type); @Override void setRecipients(Message.RecipientType type, Address[] addresses); @Override void addRecipients(Message.RecipientType type, Address[] addresses); @Override Address[] getReplyTo(); @Override void setReplyTo(Address[] addresses); @Override String getSubject(); @Override void setSubject(String subject, String charset); @Override Date getSentDate(); @Override void setSentDate(Date d); @Override Date getReceivedDate(); @Override int getSize(); long getSizeLong(); @Override int getLineCount(); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); String getInReplyTo(); @Override synchronized String getContentType(); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); @Override void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String getDescription(); @Override void setDescription(String description, String charset); @Override String getMessageID(); @Override String getFileName(); @Override void setFileName(String filename); @Override synchronized DataHandler getDataHandler(); @Override void setDataHandler(DataHandler content); @Override InputStream getMimeStream(); @Override void writeTo(OutputStream os); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); @Override synchronized Flags getFlags(); @Override synchronized boolean isSet(Flags.Flag flag); @Override synchronized void setFlags(Flags flag, boolean set); synchronized void setPeek(boolean peek); synchronized boolean getPeek(); synchronized void invalidateHeaders(); synchronized Object getItem(FetchItem fitem); } | @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("filename.csv", MimeUtility.decodeText(bp.getFileName())); } }, new IMAPHandlerMessage() { @Override public void fetch(String line) throws IOException { untagged("1 FETCH (BODYSTRUCTURE (" + "(\"text\" \"html\" (\"charset\" \"utf-8\") NIL NIL \"base64\" 402 6 NIL NIL NIL NIL)" + "(\"application\" \"octet-stream\" (\"name\" \"=?utf-8?B?ZmlsZW5hbWU=?= =?utf-8?B?LmNzdg==?=\") NIL NIL \"base64\" 658 NIL " + "(\"attachment\" (\"filename\" \"\")) NIL NIL) \"mixed\" " + "(\"boundary\" \"--boundary_539_27806e16-2599-4612-b98a-69335bedd206\") NIL NIL NIL))" ); ok(); } } ); } |
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(MimeUtility.unfold(envelope.subject)); } catch (UnsupportedEncodingException ex) { subject = envelope.subject; } return subject; } protected IMAPMessage(IMAPFolder folder, int msgnum); protected IMAPMessage(Session session); synchronized long getModSeq(); @Override Address[] getFrom(); @Override void setFrom(Address address); @Override void addFrom(Address[] addresses); @Override Address getSender(); @Override void setSender(Address address); @Override Address[] getRecipients(Message.RecipientType type); @Override void setRecipients(Message.RecipientType type, Address[] addresses); @Override void addRecipients(Message.RecipientType type, Address[] addresses); @Override Address[] getReplyTo(); @Override void setReplyTo(Address[] addresses); @Override String getSubject(); @Override void setSubject(String subject, String charset); @Override Date getSentDate(); @Override void setSentDate(Date d); @Override Date getReceivedDate(); @Override int getSize(); long getSizeLong(); @Override int getLineCount(); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); String getInReplyTo(); @Override synchronized String getContentType(); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); @Override void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String getDescription(); @Override void setDescription(String description, String charset); @Override String getMessageID(); @Override String getFileName(); @Override void setFileName(String filename); @Override synchronized DataHandler getDataHandler(); @Override void setDataHandler(DataHandler content); @Override InputStream getMimeStream(); @Override void writeTo(OutputStream os); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); @Override synchronized Flags getFlags(); @Override synchronized boolean isSet(Flags.Flag flag); @Override synchronized void setFlags(Flags flag, boolean set); synchronized void setPeek(boolean peek); synchronized boolean getPeek(); synchronized void invalidateHeaders(); synchronized Object getItem(FetchItem fitem); } | @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 MessagingException { Message m = folder.getMessage(1); assertEquals(subject, m.getSubject()); } }, new IMAPHandlerMessage() { {{ envelope = "(" + ENV_DATE + " \"" + ENV_UTF8_ENCODED_SUBJECT + "\" " + ENV_ADDRS + ")"; }} }); }
@Test public void testUtf8Subject() { 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 MessagingException { Message m = folder.getMessage(1); assertEquals(subject, m.getSubject()); } }, new IMAPHandlerMessage() { {{ envelope = "(" + ENV_DATE + " \"" + subject + "\" " + ENV_ADDRS + ")"; capabilities += " ENABLE UTF8=ACCEPT"; }} @Override public void enable(String line) throws IOException { ok(); } }); } |
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 && sType.startsWith("*"))) return true; return (subType == null && sType == null) || (subType != null && subType.equalsIgnoreCase(sType)); } ContentType(); ContentType(String primaryType, String subType,
ParameterList list); ContentType(String s); String getPrimaryType(); String getSubType(); String getBaseType(); String getParameter(String name); ParameterList getParameterList(); void setPrimaryType(String primaryType); void setSubType(String subType); void setParameter(String name, String value); void setParameterList(ParameterList list); @Override String toString(); boolean match(ContentType cType); boolean match(String s); } | @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/*")); ContentType text = new ContentType("text/*"); assertTrue(text.match(plain)); assertTrue(plain.match(text)); } |
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); @Override int getSize(); @Override int getLineCount(); @Override String getContentType(); @Override boolean isMimeType(String mimeType); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); @Override String getDescription(); @Override void setDescription(String description); void setDescription(String description, String charset); @Override String getFileName(); @Override void setFileName(String filename); @Override InputStream getInputStream(); InputStream getRawInputStream(); @Override DataHandler getDataHandler(); @Override Object getContent(); @Override void setDataHandler(DataHandler dh); @Override void setContent(Object o, String type); @Override void setText(String text); @Override void setText(String text, String charset); @Override void setText(String text, String charset, String subtype); @Override void setContent(Multipart mp); void attachFile(File file); void attachFile(String file); void attachFile(File file, String contentType, String encoding); void attachFile(String file, String contentType, String encoding); void saveFile(File file); void saveFile(String file); @Override void writeTo(OutputStream os); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); } | @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 MimeMessage(s); MimeMultipart mp = new MimeMultipart(); MimeBodyPart mbp = new MimeBodyPart() { { dh = odh; } }; mp.addBodyPart(mbp); msg.setContent(mp); msg = new MimeMessage(msg); mp = (MimeMultipart)msg.getContent(); mbp = (MimeBodyPart)mp.getBodyPart(0); assertEquals("text/x-test", mbp.getContentType()); assertEquals("quoted-printable", mbp.getEncoding()); assertEquals("test part", getString(mbp.getInputStream())); } |
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 getLineCount(); @Override String getContentType(); @Override boolean isMimeType(String mimeType); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); @Override String getDescription(); @Override void setDescription(String description); void setDescription(String description, String charset); @Override String getFileName(); @Override void setFileName(String filename); @Override InputStream getInputStream(); InputStream getRawInputStream(); @Override DataHandler getDataHandler(); @Override Object getContent(); @Override void setDataHandler(DataHandler dh); @Override void setContent(Object o, String type); @Override void setText(String text); @Override void setText(String text, String charset); @Override void setText(String text, String charset, String subtype); @Override void setContent(Multipart mp); void attachFile(File file); void attachFile(String file); void attachFile(File file, String contentType, String encoding); void attachFile(String file, String contentType, String encoding); void saveFile(File file); void saveFile(String file); @Override void writeTo(OutputStream os); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); } | @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.isMimeType("application/*")); assertFalse("wrong MIME type", mbp.isMimeType("application/test")); } |
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,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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, toAppendTo, pos); fail("No NullPointerException thrown for mask = " + mask); } catch (NullPointerException e) { } } }
@Test public void mustUseTimeZoneForFormatting() { String input = "1 Jan 2015 00:00 +0100"; SimpleDateFormat fmt = getDefault(); Date date = mustPass(fmt, input); fmt.setTimeZone(TimeZone.getTimeZone("Etc/GMT+8")); assertThat(fmt.format(date), is("Wed, 31 Dec 2014 15:00:00 -0800 (GMT-08:00)")); } |
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() : new Rfc2822StrictParser(text, pos).parse(); } MailDateFormat(); @Override MailDateFormat clone(); @Override StringBuffer format(Date date, StringBuffer dateStrBuf,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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); } catch (NullPointerException e) { } } }
@Test public void mustReturnOnInvalidParsePosition() { assertNull(getDefault().parse("", new ParsePosition(-1))); assertNull(getDefault().parse("", new ParsePosition(0))); assertNull(getDefault().parse("", new ParsePosition(1))); }
@Test public void mustFailOrSkipCfws() { String input = "(3 Jan 2015 00:00 +0000) 1 Jan 2015 00:00 +0000"; try { Date date = getStrict().parse(input); assertThatDate(date, "Thu, 1 Jan 2015 00:00:00 +0000 (UTC)"); } catch (ParseException ignored) { assertTrue("Not supporting CFWS is allowed", true); } } |
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,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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 dateStrBuf,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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, StringBuffer dateStrBuf,
FieldPosition fieldPosition); @Override Date parse(String text, ParsePosition pos); @Override void setCalendar(Calendar newCalendar); @Override void setNumberFormat(NumberFormat newNumberFormat); @Override void applyLocalizedPattern(String pattern); @Override void applyPattern(String pattern); @Override Date get2DigitYearStart(); @Override void set2DigitYearStart(Date startDate); @Override void setDateFormatSymbols(DateFormatSymbols newFormatSymbols); } | @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(getHeaderName(type)); } MimeMessage(Session session); MimeMessage(Session session, InputStream is); MimeMessage(MimeMessage source); protected MimeMessage(Folder folder, int msgnum); protected MimeMessage(Folder folder, InputStream is, int msgnum); protected MimeMessage(Folder folder, InternetHeaders headers,
byte[] content, int msgnum); @Override Address[] getFrom(); @Override void setFrom(Address address); void setFrom(String address); @Override void setFrom(); @Override void addFrom(Address[] addresses); Address getSender(); void setSender(Address address); @Override Address[] getRecipients(Message.RecipientType type); @Override Address[] getAllRecipients(); @Override void setRecipients(Message.RecipientType type, Address[] addresses); void setRecipients(Message.RecipientType type, String addresses); @Override void addRecipients(Message.RecipientType type, Address[] addresses); void addRecipients(Message.RecipientType type, String addresses); @Override Address[] getReplyTo(); @Override void setReplyTo(Address[] addresses); @Override String getSubject(); @Override void setSubject(String subject); void setSubject(String subject, String charset); @Override Date getSentDate(); @Override void setSentDate(Date d); @Override Date getReceivedDate(); @Override int getSize(); @Override int getLineCount(); @Override String getContentType(); @Override boolean isMimeType(String mimeType); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String getDescription(); @Override void setDescription(String description); void setDescription(String description, String charset); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); String getMessageID(); @Override String getFileName(); @Override void setFileName(String filename); @Override InputStream getInputStream(); InputStream getRawInputStream(); @Override synchronized DataHandler getDataHandler(); @Override Object getContent(); @Override synchronized void setDataHandler(DataHandler dh); @Override void setContent(Object o, String type); @Override void setText(String text); @Override void setText(String text, String charset); @Override void setText(String text, String charset, String subtype); @Override void setContent(Multipart mp); @Override Message reply(boolean replyToAll); Message reply(boolean replyToAll, boolean setAnswered); @Override void writeTo(OutputStream os); void writeTo(OutputStream os, String[] ignoreList); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); @Override synchronized Flags getFlags(); @Override synchronized boolean isSet(Flags.Flag flag); @Override synchronized void setFlags(Flags flag, boolean set); @Override void saveChanges(); } | @Test public void testSetRecipientStringNull() throws Exception { String addr = "[email protected]"; 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", null, m.getRecipients(TO)); } |
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); protected MimeMessage(Folder folder, InputStream is, int msgnum); protected MimeMessage(Folder folder, InternetHeaders headers,
byte[] content, int msgnum); @Override Address[] getFrom(); @Override void setFrom(Address address); void setFrom(String address); @Override void setFrom(); @Override void addFrom(Address[] addresses); Address getSender(); void setSender(Address address); @Override Address[] getRecipients(Message.RecipientType type); @Override Address[] getAllRecipients(); @Override void setRecipients(Message.RecipientType type, Address[] addresses); void setRecipients(Message.RecipientType type, String addresses); @Override void addRecipients(Message.RecipientType type, Address[] addresses); void addRecipients(Message.RecipientType type, String addresses); @Override Address[] getReplyTo(); @Override void setReplyTo(Address[] addresses); @Override String getSubject(); @Override void setSubject(String subject); void setSubject(String subject, String charset); @Override Date getSentDate(); @Override void setSentDate(Date d); @Override Date getReceivedDate(); @Override int getSize(); @Override int getLineCount(); @Override String getContentType(); @Override boolean isMimeType(String mimeType); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String getDescription(); @Override void setDescription(String description); void setDescription(String description, String charset); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); String getMessageID(); @Override String getFileName(); @Override void setFileName(String filename); @Override InputStream getInputStream(); InputStream getRawInputStream(); @Override synchronized DataHandler getDataHandler(); @Override Object getContent(); @Override synchronized void setDataHandler(DataHandler dh); @Override void setContent(Object o, String type); @Override void setText(String text); @Override void setText(String text, String charset); @Override void setText(String text, String charset, String subtype); @Override void setContent(Multipart mp); @Override Message reply(boolean replyToAll); Message reply(boolean replyToAll, boolean setAnswered); @Override void writeTo(OutputStream os); void writeTo(OutputStream os, String[] ignoreList); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); @Override synchronized Flags getFlags(); @Override synchronized boolean isSet(Flags.Flag flag); @Override synchronized void setFlags(Flags flag, boolean set); @Override void saveChanges(); } | @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(MimeMessage source); protected MimeMessage(Folder folder, int msgnum); protected MimeMessage(Folder folder, InputStream is, int msgnum); protected MimeMessage(Folder folder, InternetHeaders headers,
byte[] content, int msgnum); @Override Address[] getFrom(); @Override void setFrom(Address address); void setFrom(String address); @Override void setFrom(); @Override void addFrom(Address[] addresses); Address getSender(); void setSender(Address address); @Override Address[] getRecipients(Message.RecipientType type); @Override Address[] getAllRecipients(); @Override void setRecipients(Message.RecipientType type, Address[] addresses); void setRecipients(Message.RecipientType type, String addresses); @Override void addRecipients(Message.RecipientType type, Address[] addresses); void addRecipients(Message.RecipientType type, String addresses); @Override Address[] getReplyTo(); @Override void setReplyTo(Address[] addresses); @Override String getSubject(); @Override void setSubject(String subject); void setSubject(String subject, String charset); @Override Date getSentDate(); @Override void setSentDate(Date d); @Override Date getReceivedDate(); @Override int getSize(); @Override int getLineCount(); @Override String getContentType(); @Override boolean isMimeType(String mimeType); @Override String getDisposition(); @Override void setDisposition(String disposition); @Override String getEncoding(); @Override String getContentID(); void setContentID(String cid); @Override String getContentMD5(); @Override void setContentMD5(String md5); @Override String getDescription(); @Override void setDescription(String description); void setDescription(String description, String charset); @Override String[] getContentLanguage(); @Override void setContentLanguage(String[] languages); String getMessageID(); @Override String getFileName(); @Override void setFileName(String filename); @Override InputStream getInputStream(); InputStream getRawInputStream(); @Override synchronized DataHandler getDataHandler(); @Override Object getContent(); @Override synchronized void setDataHandler(DataHandler dh); @Override void setContent(Object o, String type); @Override void setText(String text); @Override void setText(String text, String charset); @Override void setText(String text, String charset, String subtype); @Override void setContent(Multipart mp); @Override Message reply(boolean replyToAll); Message reply(boolean replyToAll, boolean setAnswered); @Override void writeTo(OutputStream os); void writeTo(OutputStream os, String[] ignoreList); @Override String[] getHeader(String name); @Override String getHeader(String name, String delimiter); @Override void setHeader(String name, String value); @Override void addHeader(String name, String value); @Override void removeHeader(String name); @Override Enumeration<Header> getAllHeaders(); @Override Enumeration<Header> getMatchingHeaders(String[] names); @Override Enumeration<Header> getNonMatchingHeaders(String[] names); @Override void addHeaderLine(String line); @Override Enumeration<String> getAllHeaderLines(); @Override Enumeration<String> getMatchingHeaderLines(String[] names); @Override Enumeration<String> getNonMatchingHeaderLines(String[] names); @Override synchronized Flags getFlags(); @Override synchronized boolean isSet(Flags.Flag flag); @Override synchronized void setFlags(Flags flag, boolean set); @Override void saveChanges(); } | @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.getContentType()); assertEquals("quoted-printable", msg.getEncoding()); assertEquals("test message", getString(msg.getInputStream())); } |
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 r[] = new String[v.size()]; r = v.toArray(r); return (r); } InternetHeaders(); InternetHeaders(InputStream is); InternetHeaders(InputStream is, boolean allowutf8); void load(InputStream is); void load(InputStream is, boolean allowutf8); String[] getHeader(String name); String getHeader(String name, String delimiter); void setHeader(String name, String value); void addHeader(String name, String value); void removeHeader(String name); Enumeration<Header> getAllHeaders(); Enumeration<Header> getMatchingHeaders(String[] names); Enumeration<Header> getNonMatchingHeaders(String[] names); void addHeaderLine(String line); Enumeration<String> getAllHeaderLines(); Enumeration<String> getMatchingHeaderLines(String[] names); Enumeration<String> getNonMatchingHeaderLines(String[] names); } | @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 getHeader(String name, String delimiter); void setHeader(String name, String value); void addHeader(String name, String value); void removeHeader(String name); Enumeration<Header> getAllHeaders(); Enumeration<Header> getMatchingHeaders(String[] names); Enumeration<Header> getNonMatchingHeaders(String[] names); void addHeaderLine(String line); Enumeration<String> getAllHeaderLines(); Enumeration<String> getMatchingHeaderLines(String[] names); Enumeration<String> getNonMatchingHeaderLines(String[] names); } | @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(); ih.load(new AsciiStringInputStream(initialContinuationHeader)); testInitialContinuationLine(ih); } |
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( "encoded word does not include charset: " + eword); String charset = eword.substring(start, pos); int lpos = charset.indexOf('*'); if (lpos >= 0) charset = charset.substring(0, lpos); charset = javaCharset(charset); start = pos+1; if ((pos = eword.indexOf('?', start)) == -1) throw new ParseException( "encoded word does not include encoding: " + eword); String encoding = eword.substring(start, pos); start = pos+1; if ((pos = eword.indexOf("?=", start)) == -1) throw new ParseException( "encoded word does not end with \"?=\": " + eword); String word = eword.substring(start, pos); try { String decodedWord; if (word.length() > 0) { ByteArrayInputStream bis = new ByteArrayInputStream(ASCIIUtility.getBytes(word)); InputStream is; if (encoding.equalsIgnoreCase("B")) is = new BASE64DecoderStream(bis); else if (encoding.equalsIgnoreCase("Q")) is = new QDecoderStream(bis); else throw new UnsupportedEncodingException( "unknown encoding: " + encoding); int count = bis.available(); byte[] bytes = new byte[count]; count = is.read(bytes, 0, count); decodedWord = count <= 0 ? "" : new String(bytes, 0, count, charset); } else { decodedWord = ""; } if (pos + 2 < eword.length()) { String rest = eword.substring(pos + 2); if (!decodeStrict) rest = decodeInnerWords(rest); decodedWord += rest; } return decodedWord; } catch (UnsupportedEncodingException uex) { throw uex; } catch (IOException ioex) { throw new ParseException(ioex.toString()); } catch (IllegalArgumentException iex) { throw new UnsupportedEncodingException(charset); } } private MimeUtility(); static String getEncoding(DataSource ds); static String getEncoding(DataHandler dh); static InputStream decode(InputStream is, String encoding); static OutputStream encode(OutputStream os, String encoding); static OutputStream encode(OutputStream os, String encoding,
String filename); static String encodeText(String text); static String encodeText(String text, String charset,
String encoding); static String decodeText(String etext); static String encodeWord(String word); static String encodeWord(String word, String charset,
String encoding); static String decodeWord(String eword); static String quote(String word, String specials); static String fold(int used, String s); static String unfold(String s); static String javaCharset(String charset); static String mimeCharset(String charset); static String getDefaultJavaCharset(); static final int ALL; } | @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?xbfUqqLjIChFVVIpttK7u4EwhDYgKENOWSk=?="; String good = "=?gb18030?B?xbfUqqLjIChFVVIpttK7u4EwhDYgKENOWSk=?="; String goodDecoded = MimeUtility.decodeWord(good); assertEquals("gb2312", goodDecoded, MimeUtility.decodeWord(badgb2312)); assertEquals("gbk", goodDecoded, MimeUtility.decodeWord(badgbk)); assertEquals("ms936", goodDecoded, MimeUtility.decodeWord(badms936)); assertEquals("cp936", goodDecoded, MimeUtility.decodeWord(badcp936)); } |
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(); String getUsername(); String getPassword(); URL getURL(); @Override boolean equals(Object obj); @Override int hashCode(); } | @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(null, u.getFile()); } |
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.getModifiers())) { throw new NoSuchMethodException(parse.toString()); } final Method toMillis = k.getMethod("toMillis"); if (!Long.TYPE.isAssignableFrom(toMillis.getReturnType()) || Modifier.isStatic(toMillis.getModifiers())) { throw new NoSuchMethodException(toMillis.toString()); } return (Long) toMillis.invoke(parse.invoke(null, value)); } catch (final ExceptionInInitializerError EIIE) { throw wrapOrThrow(EIIE); } catch (final InvocationTargetException ite) { throw paramOrError(ite); } } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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() throws Exception { try { long ms = LogManagerProperties.parseDurationToMillis("PT20.345S"); assertEquals((20L * 1000L) + 345L, ms); } catch (ClassNotFoundException | NoClassDefFoundError ignore) { assertFalse(ignore.toString(), hasJavaTimeModule()); } }
@Test public void testParseDurationMin() throws Exception { try { long ms = LogManagerProperties.parseDurationToMillis("PT15M"); assertEquals(15L * 60L * 1000L, ms); } catch (ClassNotFoundException | NoClassDefFoundError ignore) { assertFalse(ignore.toString(), hasJavaTimeModule()); } }
@Test public void testParseDurationHour() throws Exception { try { long ms = LogManagerProperties.parseDurationToMillis("PT10H"); assertEquals(10L * 60L * 60L * 1000L, ms); } catch (ClassNotFoundException | NoClassDefFoundError ignore) { assertFalse(ignore.toString(), hasJavaTimeModule()); } }
@Test public void testParseDurationDay() throws Exception { try { long ms = LogManagerProperties.parseDurationToMillis("P2D"); assertEquals(2L * 24L * 60L * 60L * 1000L, ms); } catch (ClassNotFoundException | NoClassDefFoundError ignore) { assertFalse(ignore.toString(), hasJavaTimeModule()); } }
@Test public void testParseDurationAll() throws Exception { try { long ms = LogManagerProperties .parseDurationToMillis("P2DT3H4M20.345S"); assertEquals((2L * 24L * 60L * 60L * 1000L) + (3L * 60L * 60L * 1000L) + (4L * 60L * 1000L) + ((20L * 1000L) + 345), ms); } catch (ClassNotFoundException | NoClassDefFoundError ignore) { assertFalse(ignore.toString(), hasJavaTimeModule()); } } |
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.get(key); } } return value; } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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 = new Properties(); LogManagerProperties mp = new LogManagerProperties(parent, prefix); assertFalse(contains(mp, key, null)); assertEquals("value", mp.get(key)); assertTrue(contains(mp, key, "value")); parent.put(key, "newValue"); assertEquals("newValue", mp.get(key)); assertEquals("empty", mp.get("")); } finally { manager.reset(); } } |
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 parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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); parent = new Properties(); LogManagerProperties mp = new LogManagerProperties(parent, prefix); assertFalse(contains(mp, key, null)); assertTrue(mp.containsKey(key)); assertTrue(contains(mp, key, "value")); parent.put(key, "newValue"); assertEquals("newValue", mp.get(key)); assertTrue(mp.containsKey("")); } finally { manager.reset(); } } |
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("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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 = new Properties(); LogManagerProperties mp = new LogManagerProperties(parent, prefix); assertFalse(contains(mp, key, null)); assertEquals("value", mp.remove(key)); assertFalse(contains(mp, key, "value")); parent.put(key, "newValue"); assertEquals("newValue", mp.remove(key)); assertEquals("empty", mp.remove("")); } finally { manager.reset(); } } |
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, value); } } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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 = new Properties(); LogManagerProperties mp = new LogManagerProperties(parent, prefix); assertFalse(contains(mp, key, null)); assertEquals("value", mp.put(key, "newValue")); assertFalse(contains(mp, key, "value")); assertTrue(contains(mp, key, "newValue")); parent.put(key, "defValue"); assertEquals("newValue", mp.remove(key)); assertEquals("defValue", mp.remove(key)); assertEquals("empty", mp.put("", "")); } finally { manager.reset(); } } |
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 getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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); parent = new Properties(); LogManagerProperties mp = new LogManagerProperties(parent, prefix); assertFalse(contains(mp, key, null)); assertEquals("value", mp.setProperty(key, "newValue")); assertFalse(contains(mp, key, "value")); assertTrue(contains(mp, key, "newValue")); parent.put(key, "defValue"); assertEquals("newValue", mp.remove(key)); assertEquals("defValue", mp.remove(key)); assertEquals("empty", mp.setProperty("", "")); } finally { manager.reset(); } } |
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, b, 0); if (c.length() != 0 || (l.length() != 0 && v.length() != 0)) { b[count] = '-'; ++count; c.getChars(0, c.length(), b, count); count += c.length(); } if (v.length() != 0 && (l.length() != 0 || c.length() != 0)) { b[count] = '-'; ++count; v.getChars(0, v.length(), b, count); count += v.length(); } return String.valueOf(b, 0, count); } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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"); assertEquals("en-US-slang", LogManagerProperties.toLanguageTag(l)); l = new Locale("en", "", "slang"); assertEquals("en--slang", LogManagerProperties.toLanguageTag(l)); try { LogManagerProperties.toLanguageTag(null); fail("Null was allowed."); } catch (NullPointerException expect) { } } |
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("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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 { LogManagerProperties.newComparator(Object.class.getName()); fail("Wrong type was allowed."); } catch (ClassCastException expect) { } final Class<?> type = ErrorComparator.class; final Comparator<? super LogRecord> c = LogManagerProperties.newComparator(type.getName()); assertEquals(type, c.getClass()); setPending(new RuntimeException()); try { LogManagerProperties.newComparator(type.getName()); fail("Exception was not thrown."); } catch (InvocationTargetException expect) { assertEquals(RuntimeException.class, expect.getCause().getClass()); } finally { setPending(null); } }
@Test public void testEscapingComparator() throws Exception { try { Class<?> k = ErrorComparator.class; Comparator<? super LogRecord> c; c = LogManagerProperties.newComparator(k.getName()); assertEquals(k, c.getClass()); setPending(new ThreadDeath()); try { c = LogManagerProperties.newComparator(k.getName()); fail(String.valueOf(c)); } catch (ThreadDeath expect) { } setPending(new OutOfMemoryError()); try { c = LogManagerProperties.newComparator(k.getName()); fail(String.valueOf(c)); } catch (OutOfMemoryError expect) { } } finally { setPending(null); } } |
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.isStatic(m.getModifiers()) && Comparator.class.isAssignableFrom(m.getReturnType())) { try { reverse = (Comparator<T>) m.invoke(c); } catch (final ExceptionInInitializerError eiie) { throw wrapOrThrow(eiie); } } } catch (final NoSuchMethodException ignore) { } catch (final IllegalAccessException ignore) { } catch (final RuntimeException ignore) { } catch (final InvocationTargetException ite) { paramOrError(ite); } if (reverse == null) { reverse = Collections.reverseOrder(c); } return reverse; } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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.getClass()); assertFalse(r instanceof ErrorComparator); assertFalse(r instanceof AscComparator); assertFalse(r instanceof DescComparator); c = new AscComparator(); r = LogManagerProperties.reverseOrder(c); assertTrue(r instanceof DescComparator); c = new AscComparator(); r = LogManagerProperties.reverseOrder(c); assertTrue(r instanceof DescComparator); } |
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(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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 { LogManagerProperties.newErrorManager(Object.class.getName()); fail("Wrong type was allowed."); } catch (ClassCastException expect) { } final Class<?> type = ErrorManager.class; ErrorManager f = LogManagerProperties.newErrorManager(type.getName()); assertEquals(type, f.getClass()); setPending(new RuntimeException()); try { final String name = ErrorErrorManager.class.getName(); LogManagerProperties.newErrorManager(name); fail("Exception was not thrown."); } catch (InvocationTargetException expect) { assertEquals(RuntimeException.class, expect.getCause().getClass()); } finally { setPending(null); } }
@Test public void testEscapingErrorErrorManager() throws Exception { try { Class<?> k = ErrorErrorManager.class; ErrorManager f; f = LogManagerProperties.newErrorManager(k.getName()); assertEquals(k, f.getClass()); setPending(new ThreadDeath()); try { f = LogManagerProperties.newErrorManager(k.getName()); fail(String.valueOf(f)); } catch (ThreadDeath expect) { } setPending(new OutOfMemoryError()); try { f = LogManagerProperties.newErrorManager(k.getName()); fail(String.valueOf(f)); } catch (OutOfMemoryError expect) { } } finally { setPending(null); } } |
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 String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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.newFilter(Object.class.getName()); fail("Wrong type was allowed."); } catch (ClassCastException expect) { } final Class<?> type = ErrorFilter.class; final Filter f = LogManagerProperties.newFilter(type.getName()); assertEquals(type, f.getClass()); setPending(new RuntimeException()); try { LogManagerProperties.newFilter(type.getName()); fail("Exception was not thrown."); } catch (InvocationTargetException expect) { assertEquals(RuntimeException.class, expect.getCause().getClass()); } finally { setPending(null); } }
@Test public void testEscapingFilter() throws Exception { try { Class<?> k = ErrorFilter.class; Filter f; f = LogManagerProperties.newFilter(k.getName()); assertEquals(k, f.getClass()); setPending(new ThreadDeath()); try { f = LogManagerProperties.newFilter(k.getName()); fail(String.valueOf(f)); } catch (ThreadDeath expect) { } setPending(new OutOfMemoryError()); try { f = LogManagerProperties.newFilter(k.getName()); fail(String.valueOf(f)); } catch (OutOfMemoryError expect) { } } finally { setPending(null); } } |
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 synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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 { LogManagerProperties.newFormatter(Object.class.getName()); fail("Wrong type was allowed."); } catch (ClassCastException expect) { } final Class<?> type = SimpleFormatter.class; final Formatter f = LogManagerProperties.newFormatter(type.getName()); assertEquals(type, f.getClass()); setPending(new RuntimeException()); try { final String name = ErrorFormatter.class.getName(); LogManagerProperties.newFormatter(name); fail("Exception was not thrown."); } catch (InvocationTargetException expect) { assertEquals(RuntimeException.class, expect.getCause().getClass()); } finally { setPending(null); } }
@Test public void testEscapingFormatter() throws Exception { try { Class<?> k = ErrorFormatter.class; Formatter f; f = LogManagerProperties.newFormatter(k.getName()); assertEquals(k, f.getClass()); setPending(new ThreadDeath()); try { f = LogManagerProperties.newFormatter(k.getName()); fail(String.valueOf(f)); } catch (ThreadDeath expect) { } setPending(new OutOfMemoryError()); try { f = LogManagerProperties.newFormatter(k.getName()); fail(String.valueOf(f)); } catch (OutOfMemoryError expect) { } } finally { setPending(null); } } |
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(record), ZI_SYSTEM_DEFAULT.invoke((Object) null)); } catch (final RuntimeException ignore) { assert LR_GET_INSTANT != null && ZI_SYSTEM_DEFAULT != null : ignore; } catch (final InvocationTargetException ite) { final Throwable cause = ite.getCause(); if (cause instanceof Error) { throw (Error) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw new UndeclaredThrowableException(ite); } } catch (final Exception ignore) { } } return null; } LogManagerProperties(final Properties parent, final String prefix); @Override @SuppressWarnings("CloneDoesntCallSuperClone") synchronized Object clone(); @Override synchronized String getProperty(final String key); @Override String getProperty(final String key, final String def); @Override synchronized Object get(final Object key); @Override synchronized Object put(final Object key, final Object value); @Override Object setProperty(String key, String value); @Override synchronized boolean containsKey(final Object key); @Override synchronized Object remove(final Object key); @Override Enumeration<?> propertyNames(); @Override boolean equals(final Object o); @Override int hashCode(); } | @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<Object> c1 = (Comparable<Object>) LogManagerProperties.getZonedDateTime(r1); Comparable<Object> c2 = (Comparable<Object>) LogManagerProperties.getZonedDateTime(r2); assertEquals(k, c1.getClass()); assertEquals(k, c2.getClass()); assertNotSame(c1, c2); assertEquals(c1.getClass(), c2.getClass()); assertEquals(0, c1.compareTo(c2)); } catch (final NoSuchMethodException preJdk9) { assertNull(LogManagerProperties.getZonedDateTime(r1)); assertNull(LogManagerProperties.getZonedDateTime(r2)); assertTrue(hasJavaTimeModule()); } catch (final ClassNotFoundException preJdk8) { assertNull(LogManagerProperties.getZonedDateTime(r1)); assertNull(LogManagerProperties.getZonedDateTime(r2)); assertFalse(hasJavaTimeModule()); } }
@Test(expected=NullPointerException.class) public void testGetZonedDateTimeNull() throws Exception { LogManagerProperties.getZonedDateTime((LogRecord) null); } |
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); return true; } return isAttachmentLoggable(record); } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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 preDestroy(); void push(); @Override void flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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 = internalErrorManagerFrom(instance); instance.preDestroy(); assertEquals(1, em.exceptions.size()); assertEquals(true, em.exceptions.get(0) instanceof MessagingException); instance.close(); instance = createHandlerWithRecords(); instance.setErrorManager(new FlushErrorManager(instance)); instance.preDestroy(); instance.close(); instance = new MailHandler(2); instance.setMailProperties(createInitProperties("")); instance.setLevel(Level.ALL); instance.setErrorManager(new FlushErrorManager(instance)); instance.setPushFilter((Filter) null); instance.setPushLevel(Level.OFF); LogRecord record = new LogRecord(Level.INFO, ""); instance.publish(record); instance.preDestroy(); instance.push(); instance.close(); } |
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(); } } else { reportUnPublishedError(record); } } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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()); instance = createHandlerWithRecords(); instance.setErrorManager(new FlushErrorManager(instance)); final Level[] lvls = getAllLevels(); String SOURCE_CLASS = MailHandlerTest.class.getName(); String SOURCE_METHOD = "testPublish"; for (Level lvl : lvls) { LogRecord r = new LogRecord(lvl, ""); r.setSourceClassName(SOURCE_CLASS); r.setSourceMethodName(SOURCE_METHOD); instance.publish(r); } instance.close(); } |
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 LogRecord record); @Override void publish(final LogRecord record); void postConstruct(); void preDestroy(); void push(); @Override void flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.getLogManager(); try { read(manager, props); testAttachmentInvariants(false); } finally { manager.reset(); } }
@Test public void testAlignEmptyNames() 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.filters"), ErrorFilter.class.getName()); final LogManager manager = LogManager.getLogManager(); try { read(manager, props); testAttachmentInvariants(false); } finally { manager.reset(); } }
@Test public void testAlignEmptyFilterAndNames() throws Exception { String p = MailHandler.class.getName(); Properties props = createInitProperties(p); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName()); final LogManager manager = LogManager.getLogManager(); try { read(manager, props); testAttachmentInvariants(false); } finally { manager.reset(); } }
@Test public void testAlignErrorFilter() throws Exception { String p = MailHandler.class.getName(); Properties props = createInitProperties(p); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName() + ", " + SimpleFormatter.class.getName()); props.put(p.concat(".attachment.filters"), ErrorFilter.class.getName()); final LogManager manager = LogManager.getLogManager(); try { read(manager, props); testAttachmentInvariants(true); } finally { manager.reset(); } }
@Test public void testAlignErrorNames() 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, extra.txt"); final LogManager manager = LogManager.getLogManager(); try { read(manager, props); testAttachmentInvariants(true); } finally { manager.reset(); } }
@Test public void testAlignErrorFilterAndNames() throws Exception { String p = MailHandler.class.getName(); Properties props = createInitProperties(p); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName() + ", " + SimpleFormatter.class.getName()); props.put(p.concat(".attachment.filters"), ErrorFilter.class.getName() + "," + ErrorFilter.class.getName() + "," + ErrorFilter.class.getName()); props.put(p.concat(".attachment.names"), "att.txt, next.txt, extra.txt"); final LogManager manager = LogManager.getLogManager(); try { read(manager, props); testAttachmentInvariants(true); } finally { manager.reset(); } }
@Test public void testInitFromLogManager() throws Exception { final LogManager manager = LogManager.getLogManager(); synchronized (manager) { try { initGoodTest(MailHandler.class, new Class<?>[0], new Object[0]); initBadTest(MailHandler.class, new Class<?>[0], new Object[0]); initGoodTest(MailHandler.class, new Class<?>[]{Integer.TYPE}, new Object[]{10}); initBadTest(MailHandler.class, new Class<?>[]{Integer.TYPE}, new Object[]{100}); initGoodTest(MailHandler.class, new Class<?>[]{Properties.class}, new Object[]{new Properties()}); initBadTest(MailHandler.class, new Class<?>[]{Properties.class}, new Object[]{new Properties()}); initGoodTest(MailHandlerExt.class, new Class<?>[0], new Object[0]); initBadTest(MailHandlerExt.class, new Class<?>[0], new Object[0]); initGoodTest(MailHandlerExt.class, new Class<?>[]{Integer.TYPE}, new Object[]{10}); initBadTest(MailHandlerExt.class, new Class<?>[]{Integer.TYPE}, new Object[]{100}); initGoodTest(MailHandlerExt.class, new Class<?>[]{Properties.class}, new Object[]{new Properties()}); initBadTest(MailHandlerExt.class, new Class<?>[]{Properties.class}, new Object[]{new Properties()}); } finally { manager.reset(); } } } |
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); @Deprecated static int getIntSessionProperty(Session session,
String name, int def); @Deprecated static boolean getBooleanSessionProperty(Session session,
String name, boolean def); static boolean getBooleanSystemProperty(String name, boolean def); } | @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, "test", true)); }
@Test public void testBoolDefProp() throws Exception { Properties defprops = new Properties(); defprops.setProperty("test", "true"); Properties props = new Properties(defprops); assertTrue(PropUtil.getBooleanProperty(props, "test", false)); }
@Test public void testBoolean() throws Exception { Properties props = new Properties(); props.put("test", true); assertTrue(PropUtil.getBooleanProperty(props, "test", false)); } |
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(); void push(); @Override void flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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 = internalErrorManagerFrom(instance); instance.push(); assertEquals(1, em.exceptions.size()); assertEquals(true, em.exceptions.get(0) instanceof MessagingException); instance.close(); instance = createHandlerWithRecords(); instance.setErrorManager(new PushErrorManager(instance)); instance.push(); instance.close(); instance = new MailHandler(1); instance.setMailProperties(createInitProperties("")); instance.setLevel(Level.ALL); instance.setErrorManager(new PushErrorManager(instance)); instance.setPushFilter((Filter) null); instance.setPushLevel(Level.INFO); LogRecord record = new LogRecord(Level.SEVERE, ""); instance.publish(record); instance.close(); } |
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 preDestroy(); void push(); @Override void flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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 = internalErrorManagerFrom(instance); instance.flush(); assertEquals(1, em.exceptions.size()); assertEquals(true, em.exceptions.get(0) instanceof MessagingException); instance.close(); instance = createHandlerWithRecords(); instance.setErrorManager(new FlushErrorManager(instance)); instance.flush(); instance.close(); instance = new MailHandler(1); instance.setMailProperties(createInitProperties("")); instance.setLevel(Level.ALL); instance.setErrorManager(new FlushErrorManager(instance)); instance.setPushFilter((Filter) null); instance.setPushLevel(Level.SEVERE); LogRecord record = new LogRecord(Level.INFO, ""); instance.publish(record); instance.push(); instance.close(); } |
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) { this.data = new LogRecord[1]; this.matched = new int[this.data.length]; } } } if (msg != null) { send(msg, false, ErrorManager.CLOSE_FAILURE); } } catch (final LinkageError JDK8152515) { reportLinkageError(JDK8152515, 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 preDestroy(); void push(); @Override void flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.setLevel(Level.ALL); assertEquals(true, instance.isLoggable(record)); instance.close(); assertEquals(false, instance.isLoggable(record)); assertEquals(Level.OFF, instance.getLevel()); instance.setLevel(Level.ALL); assertEquals(Level.OFF, instance.getLevel()); assertEquals(capacity, instance.getCapacity()); assertEquals(true, em.exceptions.isEmpty()); instance = createHandlerWithRecords(); em = internalErrorManagerFrom(instance); instance.close(); assertEquals(1, em.exceptions.size()); assertEquals(true, em.exceptions.get(0) instanceof MessagingException); instance = createHandlerWithRecords(); instance.setErrorManager(new FlushErrorManager(instance)); instance.close(); }
@Test public void testMailDebugLowCap() throws Exception { MailHandler instance = new MailHandler(1); try { testMailDebug(instance, 2); } finally { instance.close(); } }
@Test public void testMailDebugPush() throws Exception { MailHandler instance = new MailHandler(4); try { testMailDebug(instance, -3); } finally { instance.close(); } }
@Test public void testMailDebugFlush() throws Exception { MailHandler instance = new MailHandler(3); try { testMailDebug(instance, -2); } finally { instance.close(); } }
@Test public void testMailDebugClose() throws Exception { MailHandler instance = new MailHandler(1000); try { testMailDebug(instance, -1); } finally { instance.close(); } } |
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 ByteArrayInputStream in = new ByteArrayInputStream(b); assert in.markSupported() : in.getClass().getName(); return URLConnection.guessContentTypeFromStream(in); } catch (final IOException IOE) { reportError(IOE.getMessage(), IOE, ErrorManager.FORMAT_FAILURE); } } return null; } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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)); assertEquals("application/xml", head); instance.setEncoding("US-ASCII"); head = instance.contentTypeOf(new XMLFormatter().getHead(instance)); assertEquals("application/xml", head); instance.setEncoding((String) null); head = instance.contentTypeOf(new SimpleFormatter().getHead(instance)); assertNull(head); instance.setEncoding("US-ASCII"); head = instance.contentTypeOf(new SimpleFormatter().getHead(instance)); assertNull(head); instance.setEncoding((String) null); head = instance.contentTypeOf(new HeadFormatter("<HTML><BODY>").getHead(instance)); assertEquals("text/html", head); instance.setEncoding((String) null); head = instance.contentTypeOf(new HeadFormatter("<html><body>").getHead(instance)); assertEquals("text/html", head); instance.setEncoding("US-ASCII"); head = instance.contentTypeOf(new HeadFormatter("<HTML><BODY>").getHead(instance)); assertEquals("text/html", head); instance.setEncoding("US-ASCII"); head = instance.contentTypeOf(new HeadFormatter("<HTML><HEAD></HEAD>" + "<BODY></BODY></HTML>").getHead(instance)); assertEquals("text/html", head); instance.setEncoding((String) null); head = instance.contentTypeOf(new HeadFormatter("Head").getHead(instance)); if (head != null) { assertEquals("text/plain", head); } instance.setEncoding("US-ASCII"); head = instance.contentTypeOf(new HeadFormatter("Head").getHead(instance)); if (head != null) { assertEquals("text/plain", head); } instance.setEncoding("US-ASCII"); head = instance.contentTypeOf(new HeadFormatter("Head.......Neck.......Body").getHead(instance)); if (head != null) { assertEquals("text/plain", head); } instance.close(); for (Exception exception : em.exceptions) { fail(exception.toString()); } } |
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) { reportLinkageError(GLASSFISH_21258, code); } } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.setErrorManager(new ErrorManager() { @Override public void error(String msg, Exception ex, int code) { assertEquals(msg.indexOf(Level.SEVERE.getName()), 0); } }); instance.reportError("simple message.", null, ErrorManager.GENERIC_FAILURE); instance.close(); instance = createHandlerWithRecords(); instance.setErrorManager(new MessageErrorManager(instance.getMailProperties()) { @Override protected void error(MimeMessage message, Throwable t, int code) { try { assertTrue(message.getHeader("X-Mailer")[0].startsWith(MailHandler.class.getName())); assertTrue(null != message.getSentDate()); message.saveChanges(); } catch (MessagingException ME) { fail(ME.toString()); } } }); instance.close(); } |
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) { throw RE; } catch (final Exception noContent) { final String txt = noContent.getMessage(); if (!isEmpty(txt)) { int limit = 0; while (t != null) { if (noContent.getClass() == t.getClass() && txt.equals(t.getMessage())) { return true; } final Throwable cause = t.getCause(); if (cause == null && t instanceof MessagingException) { t = ((MessagingException) t).getNextException(); } else { t = cause; } if (++limit == (1 << 16)) { break; } } } } finally { getAndSetContextClassLoader(ccl); } return false; } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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); msg.setRecipients(Message.RecipientType.TO, from); msg.setHeader("Content-Transfer-Encoding", "base64"); msg.saveChanges(); try { msg.writeTo(new ByteArrayOutputStream(384)); fail("Verify type 'remote' may hide remote exceptions."); } catch (RuntimeException re) { throw re; } catch (Exception expect) { assertNotNull(expect.getMessage()); assertTrue(expect.getMessage().length() != 0); assertTrue(target.isMissingContent(msg, expect)); assertTrue(target.isMissingContent(msg, new Exception(expect))); assertTrue(target.isMissingContent(msg, new MessagingException("", expect))); assertFalse(target.isMissingContent(msg, new Exception())); assertFalse(target.isMissingContent(msg, new RuntimeException())); } } |
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 { canidate = this.filter; result = intern(seen, canidate); if (result != canidate && result instanceof Filter) { this.filter = (Filter) result; } canidate = this.formatter; result = intern(seen, canidate); if (result != canidate && result instanceof Formatter) { this.formatter = (Formatter) result; } } catch (final SecurityException se) { reportError(se.getMessage(), se, ErrorManager.OPEN_FAILURE); } canidate = this.subjectFormatter; result = intern(seen, canidate); if (result != canidate && result instanceof Formatter) { this.subjectFormatter = (Formatter) result; } canidate = this.pushFilter; result = intern(seen, canidate); if (result != canidate && result instanceof Filter) { this.pushFilter = (Filter) result; } for (int i = 0; i < attachmentFormatters.length; ++i) { canidate = attachmentFormatters[i]; result = intern(seen, canidate); if (result != canidate && result instanceof Formatter) { attachmentFormatters[i] = (Formatter) result; } canidate = attachmentFilters[i]; result = intern(seen, canidate); if (result != canidate && result instanceof Filter) { attachmentFilters[i] = (Filter) result; } canidate = attachmentNames[i]; result = intern(seen, canidate); if (result != canidate && result instanceof Formatter) { attachmentNames[i] = (Formatter) result; } } } catch (final Exception skip) { reportError(skip.getMessage(), skip, ErrorManager.OPEN_FAILURE); } catch (final LinkageError skip) { reportError(skip.getMessage(), new InvocationTargetException(skip), ErrorManager.OPEN_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(); void push(); @Override void flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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"), InternFilterFormatterComparator.class.getName()); props.put(p.concat(".filter"), InternFilter.class.getName()); props.put(p.concat(".pushFilter"), InternFilterErrorManager.class.getName()); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName() + ", " + InternFilterFormatter.class.getName() + ", " + InternFormatter.class.getName() + ", " + XMLFormatter.class.getName() + ", " + InternFormatter.class.getName() + ", " + SimpleFormatter.class.getName() + ", " + SimpleFormatter.class.getName()); props.put(p.concat(".attachment.filters"), null + ", " + InternFilterFormatter.class.getName() + ", " + InternFilterFormatter.class.getName() + ", " + InternFilter.class.getName() + ", " + InternFilter.class.getName() + ", " + InternBadSubFilter.class.getName() + ", " + InternBadFilter.class.getName()); final String txt = "Intern test"; props.put(p.concat(".attachment.names"), txt + ", " + InternFilterFormatter.class.getName() + ", " + InternFilterFormatter.class.getName() + ", " + txt + ", " + InternFormatter.class.getName() + ", " + InternFilterFormatterComparator.class.getName() + ", " + InternFilterFormatterComparator.class.getName()); props.put(p.concat(".subject"), txt); MailHandler instance = testIntern(p, props); instance.close(); Formatter[] formatter = instance.getAttachmentFormatters(); Filter[] filter = instance.getAttachmentFilters(); Formatter[] names = instance.getAttachmentNames(); assertSame(instance.getErrorManager(), instance.getPushFilter()); assertNull(filter[0]); assertSame(filter[1], filter[2]); assertSame(filter[1], formatter[1]); assertSame(filter[2], formatter[1]); assertSame(names[1], filter[1]); assertSame(names[1], formatter[1]); assertSame(names[2], filter[2]); assertSame(names[2], formatter[1]); assertSame(names[1], filter[2]); assertNotNull(instance.getSubject()); assertSame(instance.getSubject(), names[0]); assertSame(instance.getSubject(), names[3]); assertSame(names[0], names[3]); assertNotNull(instance.getFilter()); assertSame(instance.getFilter(), filter[3]); assertSame(instance.getFilter(), filter[4]); assertSame(filter[3], filter[4]); assertNotSame(filter[5], filter[6]); assertNotNull(instance.getComparator()); assertNotSame(instance.getComparator(), names[5]); assertNotSame(instance.getComparator(), names[6]); assertSame(names[5], names[6]); InternalErrorManager em = internalErrorManagerFrom(instance); for (Exception exception : em.exceptions) { final Throwable t = exception; if (t instanceof IllegalArgumentException && String.valueOf(t.getMessage()).contains("equal")) { continue; } dump(t); } assertFalse(em.exceptions.isEmpty()); } |
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"); session.getProperty("mail." + protocol + ".dsn.notify"); session.getProperty("mail." + protocol + ".port"); session.getProperty("mail.user"); session.getProperty("mail." + protocol + ".user"); session.getProperty("mail." + protocol + ".localport"); } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.setMailProperties(props); for (Exception exception : em.exceptions) { final Throwable t = exception; if (t instanceof AddressException == false) { dump(t); fail(t.toString()); } } } finally { instance.close(); } props.put("verify", "local"); instance = new MailHandler(); try { em = new InternalErrorManager(); instance.setErrorManager(em); instance.setMailProperties(props); for (Exception exception : em.exceptions) { final Throwable t = exception; if (t instanceof AddressException == false) { dump(t); fail(t.toString()); } } } finally { instance.close(); } props.put("verify", "resolve"); instance = new MailHandler(); try { em = new InternalErrorManager(); instance.setErrorManager(em); instance.setMailProperties(props); for (Exception exception : em.exceptions) { final Throwable t = exception; if (isConnectOrTimeout(t)) { continue; } if (t instanceof AddressException == false) { dump(t); fail(t.toString()); } } } finally { instance.close(); } props.put("verify", "login"); instance = new MailHandler(); try { em = new InternalErrorManager(); instance.setErrorManager(em); instance.setMailProperties(props); for (Exception exception : em.exceptions) { final Throwable t = exception; if (isConnectOrTimeout(t)) { continue; } if (t instanceof AddressException == false) { dump(t); fail(t.toString()); } } } finally { instance.close(); } props.put("verify", "remote"); instance = new MailHandler(); try { em = new InternalErrorManager(); instance.setErrorManager(em); instance.setMailProperties(props); for (Exception exception : em.exceptions) { final Throwable t = exception; if (t instanceof AddressException) { continue; } else if (isConnectOrTimeout(t)) { continue; } else { dump(t); fail(t.toString()); } } } finally { instance.close(); } } |
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(name); } catch (final SecurityException SE) { throw SE; } catch (ClassNotFoundException | ClassCastException literalSubject) { this.subjectFormatter = TailNameFormatter.of(name); } catch (final Exception E) { this.subjectFormatter = TailNameFormatter.of(name); reportError(E.getMessage(), E, ErrorManager.OPEN_FAILURE); } } else { this.subjectFormatter = TailNameFormatter.of(name); } } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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()); props.put(p.concat(".subject"), Properties.class.getName()); read(manager, props); try { target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } props.put(p.concat(".subject"), ThrowFormatter.class.getName().toUpperCase(Locale.US)); read(manager, props); target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } props.put(p.concat(".subject"), Properties.class.getName().toUpperCase(Locale.US)); read(manager, props); target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } } finally { manager.reset(); } } |
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, Authenticator.class); } catch (final SecurityException SE) { throw SE; } catch (final ClassNotFoundException | ClassCastException literalAuth) { this.auth = DefaultAuthenticator.of(name); } catch (final Exception E) { reportError(E.getMessage(), E, ErrorManager.OPEN_FAILURE); } } else { this.auth = DefaultAuthenticator.of(name); } } } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.length]; for (int i = 0; i < a.length; ++i) { names[i] = names[i].trim(); if (!"null".equalsIgnoreCase(names[i])) { try { a[i] = LogManagerProperties.newFilter(names[i]); } catch (final SecurityException SE) { throw SE; } catch (final Exception E) { reportError(E.getMessage(), E, ErrorManager.OPEN_FAILURE); } } } this.attachmentFilters = a; if (alignAttachmentFilters()) { reportError("Attachment filters.", attachmentMismatch("Length mismatch."), ErrorManager.OPEN_FAILURE); } } else { this.attachmentFilters = emptyFilterArray(); alignAttachmentFilters(); } } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.class.getName()); props.put(p.concat(".filter"), ErrorFilter.class.getName()); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName()); props.put(p.concat(".attachment.names"), Properties.class.getName()); assertNull(props.getProperty(p.concat(".attachment.filters"))); read(manager, props); try { target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } } finally { manager.reset(); } assertEquals(ErrorFilter.class, target.getFilter().getClass()); assertEquals(target.getFilter(), target.getAttachmentFilters()[0]); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName() + ", " + SimpleFormatter.class.getName() + ", " + SimpleFormatter.class.getName() + ", " + SimpleFormatter.class.getName()); props.put(p.concat(".attachment.names"), "a.txt, b.txt, c.txt, d.txt"); props.put(p.concat(".attachment.filters"), "null, " + ThrowFilter.class.getName()); read(manager, props); try { target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { final Throwable t = exception; if (t instanceof IndexOutOfBoundsException) { continue; } dump(t); } assertFalse(em.exceptions.isEmpty()); } finally { target.close(); } } finally { manager.reset(); } assertEquals(ErrorFilter.class, target.getFilter().getClass()); assertNull(target.getAttachmentFilters()[0]); assertEquals(ThrowFilter.class, target.getAttachmentFilters()[1].getClass()); assertEquals(target.getFilter(), target.getAttachmentFilters()[2]); assertEquals(target.getFilter(), target.getAttachmentFilters()[3]); } |
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[names.length]; for (int i = 0; i < a.length; ++i) { names[i] = names[i].trim(); if (!"null".equalsIgnoreCase(names[i])) { try { try { a[i] = LogManagerProperties.newFormatter(names[i]); } catch (ClassNotFoundException | ClassCastException literal) { a[i] = TailNameFormatter.of(names[i]); } } catch (final SecurityException SE) { throw SE; } catch (final Exception E) { reportError(E.getMessage(), E, ErrorManager.OPEN_FAILURE); } } else { final Exception NPE = new NullPointerException(atIndexMsg(i)); reportError("Attachment names.", NPE, ErrorManager.OPEN_FAILURE); } } this.attachmentNames = a; if (alignAttachmentNames()) { reportError("Attachment names.", attachmentMismatch("Length mismatch."), ErrorManager.OPEN_FAILURE); } } else { this.attachmentNames = emptyFormatterArray(); alignAttachmentNames(); } } 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 flush(); @Override void close(); @Override void setLevel(final Level newLevel); @Override Level getLevel(); @Override ErrorManager getErrorManager(); @Override void setErrorManager(final ErrorManager em); @Override Filter getFilter(); @Override void setFilter(final Filter newFilter); @Override synchronized String getEncoding(); @Override void setEncoding(String encoding); @Override synchronized Formatter getFormatter(); @Override synchronized void setFormatter(Formatter newFormatter); final synchronized Level getPushLevel(); final synchronized void setPushLevel(final Level level); final synchronized Filter getPushFilter(); final synchronized void setPushFilter(final Filter filter); final synchronized Comparator<? super LogRecord> getComparator(); final synchronized void setComparator(Comparator<? super LogRecord> c); final synchronized int getCapacity(); final synchronized Authenticator getAuthenticator(); final void setAuthenticator(final Authenticator auth); final void setAuthenticator(final char... password); final void setMailProperties(Properties props); final Properties getMailProperties(); final Filter[] getAttachmentFilters(); final void setAttachmentFilters(Filter... filters); final Formatter[] getAttachmentFormatters(); final void setAttachmentFormatters(Formatter... formatters); final Formatter[] getAttachmentNames(); final void setAttachmentNames(final String... names); final void setAttachmentNames(Formatter... formatters); final synchronized Formatter getSubject(); final void setSubject(final String subject); final void setSubject(final Formatter format); } | @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.getName()); props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName()); props.put(p.concat(".attachment.names"), Properties.class.getName()); read(manager, props); try { target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName()); props.put(p.concat(".attachment.names"), SimpleFormatter.class.getName().toUpperCase(Locale.US)); read(manager, props); target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } props.put(p.concat(".attachment.formatters"), SimpleFormatter.class.getName()); props.put(p.concat(".attachment.names"), Properties.class.getName().toUpperCase(Locale.US)); read(manager, props); target = new MailHandler(); try { em = internalErrorManagerFrom(target); for (Exception exception : em.exceptions) { dump(exception); } assertTrue(em.exceptions.isEmpty()); } finally { target.close(); } } finally { manager.reset(); } } |
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 = cause; } if (normal == null && cause instanceof Error) { high = cause; } if (++limit == (1 << 16)) { break; } } return high != null ? high : normal != null ? normal : root; } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); } | @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().initCause(next); Throwable reduced = a.apply(next); assertEquals(Error.class, reduced.getClass()); }
@Test(timeout = 30000) public void testApplyEvil() { SeverityComparator a = new SeverityComparator(); final int len = 7; final Class<? extends Throwable> type = Exception.class; Throwable l = a.apply(createEvilThrowable(type, len)); assertEquals(type, l.getClass()); }
@Test public void testApplyProxyNormal() { SeverityComparator a = new SeverityComparator(); Throwable next = this.headIeChain(new AssertionError()); next = new UndeclaredThrowableException(next); Throwable reduced = a.apply(next); assertEquals(InterruptedException.class, reduced.getClass()); }
@Test public void testApplyReflectNormal() { SeverityComparator a = new SeverityComparator(); Throwable next = this.headIeChain(new AssertionError()); next = new InvocationTargetException(next); Throwable reduced = a.apply(next); assertEquals(InterruptedException.class, reduced.getClass()); }
@Test public void testApplyNormalByNormal() { SeverityComparator a = new SeverityComparator(); Throwable next = this.headIeChain(new AssertionError()); next = new Error(next); next = this.headIioeChain(next); next = new ExecutionException(next); Throwable reduced = a.apply(next); assertEquals(InterruptedException.class, reduced.getClass()); }
@Test public void testApplyFindsRootCause() { SeverityComparator a = new SeverityComparator(); final Throwable root = new Exception(); Throwable next = root; for (int i = 0; i < 7; i++) { next = new RuntimeException(next); } Throwable reduced = a.apply(next); assertEquals(root, reduced); } |
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()) { return 0; } if (isNormal(t1)) { return isNormal(t2) ? 0 : -1; } else { if (isNormal(t2)) { return 1; } } if (t1 instanceof Error) { return t2 instanceof Error ? 0 : 1; } else if (t1 instanceof RuntimeException) { return t2 instanceof Error ? -1 : t2 instanceof RuntimeException ? 0 : 1; } else { return t2 instanceof Error || t2 instanceof RuntimeException ? -1 : 0; } } } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); } | @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); assertTrue(a.compareThrowable(tc1, tc2) > 0); assertTrue(a.compareThrowable(tc2, tc1) < 0); }
@Test public void testCompareThrownNull() { SeverityComparator a = new SeverityComparator(); assertEquals(0, a.compareThrowable((Throwable) null, (Throwable) null)); assertTrue(a.compareThrowable(new Throwable(), (Throwable) null) > 0); assertTrue(a.compareThrowable((Throwable) null, new Throwable()) < 0); } |
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 compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); } | @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); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); } | @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)) { if (c.getName().equals("java.lang.ThreadDeath")) { return true; } } else { if (c.getName().contains("Interrupt")) { return true; } } } return false; } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); } | @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.headSubIeChain(null))); assertTrue(a.isNormal(this.headSubIioeChain(null))); assertTrue(a.isNormal(this.headSubTdChain(null))); assertTrue(a.isNormal(this.headSubTdChain(null))); assertTrue(a.isNormal(this.headWidChain(null))); assertTrue(a.isNormal(this.headWitChain(null))); }
@Test public void testIsNormalEvil() { SeverityComparator a = new SeverityComparator(); assertFalse(a.isNormal(createEvilThrowable(Exception.class, 7))); }
@Test public void testIsNormalDoesNotUseApply() { SeverityComparator a = new SeverityComparator(); Throwable next = this.headIeChain(new AssertionError()); next = new Error(next); next = this.headIioeChain(next); next = new ExecutionException(next); assertFalse(a.isNormal(next)); }
@Test public void testIsNormalNull() { SeverityComparator a = new SeverityComparator(); assertFalse(a.isNormal((Throwable) null)); } |
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()); if (cmp == 0) { cmp = applyThenCompare(o1.getThrown(), o2.getThrown()); if (cmp == 0) { cmp = compare(o1.getSequenceNumber(), o2.getSequenceNumber()); if (cmp == 0) { cmp = compare(o1.getMillis(), o2.getMillis()); } } } return cmp; } Throwable apply(final Throwable chain); final int applyThenCompare(Throwable tc1, Throwable tc2); int compareThrowable(final Throwable t1, final Throwable t2); @SuppressWarnings("override") //JDK-6954234 int compare(final LogRecord o1, final LogRecord o2); @Override boolean equals(final Object o); @Override int hashCode(); boolean isNormal(final Throwable t); } | @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... buffers); static CompositeBuffer newBuffer(final MemoryManager memoryManager,
final Buffer[] buffers, final boolean isReadOnly); DisposeOrder disposeOrder(); CompositeBuffer disposeOrder(final DisposeOrder disposeOrder); abstract CompositeBuffer append(Buffer buffer); @Override abstract CompositeBuffer prepend(Buffer buffer); @Override abstract Object[] underlying(); abstract void removeAll(); abstract void allowInternalBuffersDispose(boolean allow); abstract boolean allowInternalBuffersDispose(); abstract int bulk(BulkOperation operation); abstract int bulk(BulkOperation operation, int position, int limit); abstract boolean replace(Buffer oldBuffer, Buffer newBuffer); } | @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.split(2); assertMarkExceptionThrown(composite); assertMarkExceptionThrown(otherHalf); }
@Test public void testToByteBufferArray() { final byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final List<Buffer> bufferList = new ArrayList<Buffer>(); for (byte b : bytes) { final Buffer buffer = mm.allocate(1); buffer.put(0, b); bufferList.add(buffer); } final Buffer[] buffers = bufferList.toArray(new Buffer[bufferList.size()]); final CompositeBuffer composite = CompositeBuffer.newBuffer(mm, buffers); for (int i = 0; i < bytes.length; i++) { for (int j = i; j < bytes.length; j++) { final ByteBufferArray bbArray = composite.toByteBufferArray(i, j); int bytesChecked = 0; final ByteBuffer[] bbs = bbArray.getArray(); for (int k = 0; k < bbArray.size(); k++) { final ByteBuffer bb = bbs[k]; while (bb.hasRemaining()) { final byte got = bb.get(); assertEquals("Testcase [pos=" + i + " lim=" + j + " bytenumber=" + bytesChecked + "]", bytes[i + bytesChecked], got); bytesChecked++; } } assertEquals(j - i, bytesChecked); bbArray.restore(); } } }
@Test public void testToByteBuffer() { final byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final List<Buffer> bufferList = new ArrayList<Buffer>(); for (byte b : bytes) { final Buffer buffer = mm.allocate(1); buffer.put(0, b); bufferList.add(buffer); } final Buffer[] buffers = bufferList.toArray(new Buffer[bufferList.size()]); final CompositeBuffer composite = CompositeBuffer.newBuffer(mm, buffers); for (int i = 0; i < bytes.length; i++) { for (int j = i; j < bytes.length; j++) { final ByteBuffer bb = composite.toByteBuffer(i, j); int bytesChecked = 0; while (bb.hasRemaining()) { final byte got = bb.get(); assertEquals("Testcase [pos=" + i + " lim=" + j + " bytenumber=" + bytesChecked + "]", bytes[i + bytesChecked], got); bytesChecked++; } assertEquals(j - i, bytesChecked); } } }
@Test public void testToStringContent2() { final Charset utf16 = Charset.forName("UTF-16"); final String msg = "\u043F\u0440\u0438\u0432\u0435\u0442"; final Buffer msgBuffer = Buffers.wrap(mm, msg, utf16); final Buffer b1 = msgBuffer.duplicate(); final Buffer b2 = b1.split(3); final CompositeBuffer composite = CompositeBuffer.newBuffer( mm, b1, b2); assertTrue(composite.equals(msgBuffer)); assertEquals(msg, composite.toStringContent(utf16)); }
@Test public void testGetByteBuffer() { final byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; final List<Buffer> bufferList = new ArrayList<Buffer>(); for (byte b : bytes) { final Buffer buffer = mm.allocate(1); buffer.put(0, b); bufferList.add(buffer); } final Buffer[] buffers = bufferList.toArray(new Buffer[bufferList.size()]); final CompositeBuffer composite = CompositeBuffer.newBuffer(mm, buffers); final ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length * 2); final int position = byteBuffer.remaining() / 4; for (int i = 0; i < bytes.length; i++) { Buffers.setPositionLimit(composite, 0, i); Buffers.setPositionLimit(byteBuffer, position, position + i); composite.get(byteBuffer); Buffers.setPositionLimit(composite, 0, i); Buffers.setPositionLimit(byteBuffer, position, position + i); assertTrue(composite.equals(Buffers.wrap(mm, byteBuffer))); } } |
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 setSerialized(int n, boolean newValue); int indexOf(String name, int fromIndex); int indexOf(final Header header, final int fromIndex); boolean contains(final Header header); boolean contains(final String header); Iterable<String> names(); Iterable<String> trailerNames(); Iterable<String> values(final String name); Iterable<String> values(final Header name); Iterable<String> trailerValues(final String name); @SuppressWarnings("unused") Iterable<String> trailerValues(final Header name); DataChunk addValue(String name); DataChunk addValue(final Header header); DataChunk addValue(final byte[] buffer, final int startN,
final int len); DataChunk addValue(final Buffer buffer, final int startN,
final int len); DataChunk setValue(final String name); DataChunk setValue(final Header header); DataChunk getValue(String name); DataChunk getValue(final Header header); String getHeader(String name); String getHeader(final Header header); void removeHeader(String name); void removeHeader(final Header header); @SuppressWarnings("UnusedDeclaration") void removeHeader(final String name, final String str); @SuppressWarnings("UnusedDeclaration") void removeHeaderMatches(final String name, final String regex); void removeHeaderMatches(final Header header, final String regex); void setMaxNumHeaders(int maxNumHeaders); @SuppressWarnings("unused") int getMaxNumHeaders(); static final int MAX_NUM_HEADERS_UNBOUNDED; static final int MAX_NUM_HEADERS_DEFAULT; static final int DEFAULT_HEADER_SIZE; static DataChunk NOOP_CHUNK; } | @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, list.toArray(new String[list.size()])); } |
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); int size(); int trailerSize(); DataChunk getName(int n); DataChunk getValue(int n); boolean isSerialized(int n); boolean setSerialized(int n, boolean newValue); int indexOf(String name, int fromIndex); int indexOf(final Header header, final int fromIndex); boolean contains(final Header header); boolean contains(final String header); Iterable<String> names(); Iterable<String> trailerNames(); Iterable<String> values(final String name); Iterable<String> values(final Header name); Iterable<String> trailerValues(final String name); @SuppressWarnings("unused") Iterable<String> trailerValues(final Header name); DataChunk addValue(String name); DataChunk addValue(final Header header); DataChunk addValue(final byte[] buffer, final int startN,
final int len); DataChunk addValue(final Buffer buffer, final int startN,
final int len); DataChunk setValue(final String name); DataChunk setValue(final Header header); DataChunk getValue(String name); DataChunk getValue(final Header header); String getHeader(String name); String getHeader(final Header header); void removeHeader(String name); void removeHeader(final Header header); @SuppressWarnings("UnusedDeclaration") void removeHeader(final String name, final String str); @SuppressWarnings("UnusedDeclaration") void removeHeaderMatches(final String name, final String regex); void removeHeaderMatches(final Header header, final String regex); void setMaxNumHeaders(int maxNumHeaders); @SuppressWarnings("unused") int getMaxNumHeaders(); static final int MAX_NUM_HEADERS_UNBOUNDED; static final int MAX_NUM_HEADERS_DEFAULT; static final int DEFAULT_HEADER_SIZE; static DataChunk NOOP_CHUNK; } | @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 String[list.size()])); } |
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 MimeHeaders source); int size(); int trailerSize(); DataChunk getName(int n); DataChunk getValue(int n); boolean isSerialized(int n); boolean setSerialized(int n, boolean newValue); int indexOf(String name, int fromIndex); int indexOf(final Header header, final int fromIndex); boolean contains(final Header header); boolean contains(final String header); Iterable<String> names(); Iterable<String> trailerNames(); Iterable<String> values(final String name); Iterable<String> values(final Header name); Iterable<String> trailerValues(final String name); @SuppressWarnings("unused") Iterable<String> trailerValues(final Header name); DataChunk addValue(String name); DataChunk addValue(final Header header); DataChunk addValue(final byte[] buffer, final int startN,
final int len); DataChunk addValue(final Buffer buffer, final int startN,
final int len); DataChunk setValue(final String name); DataChunk setValue(final Header header); DataChunk getValue(String name); DataChunk getValue(final Header header); String getHeader(String name); String getHeader(final Header header); void removeHeader(String name); void removeHeader(final Header header); @SuppressWarnings("UnusedDeclaration") void removeHeader(final String name, final String str); @SuppressWarnings("UnusedDeclaration") void removeHeaderMatches(final String name, final String regex); void removeHeaderMatches(final Header header, final String regex); void setMaxNumHeaders(int maxNumHeaders); @SuppressWarnings("unused") int getMaxNumHeaders(); static final int MAX_NUM_HEADERS_UNBOUNDED; static final int MAX_NUM_HEADERS_DEFAULT; static final int DEFAULT_HEADER_SIZE; static DataChunk NOOP_CHUNK; } | @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.assertArrayEquals(expectedValuesSet1, list.toArray(new String[list.size()])); result = mimeHeaders.values("custom-before-2"); list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedValuesSet2, list.toArray(new String[list.size()])); result = mimeHeaders.values("custom-after"); list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedValuesSet1, list.toArray(new String[list.size()])); result = mimeHeaders.values("custom-after-2"); list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedValuesSet2, list.toArray(new String[list.size()])); } |
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(final MimeHeaders source); int size(); int trailerSize(); DataChunk getName(int n); DataChunk getValue(int n); boolean isSerialized(int n); boolean setSerialized(int n, boolean newValue); int indexOf(String name, int fromIndex); int indexOf(final Header header, final int fromIndex); boolean contains(final Header header); boolean contains(final String header); Iterable<String> names(); Iterable<String> trailerNames(); Iterable<String> values(final String name); Iterable<String> values(final Header name); Iterable<String> trailerValues(final String name); @SuppressWarnings("unused") Iterable<String> trailerValues(final Header name); DataChunk addValue(String name); DataChunk addValue(final Header header); DataChunk addValue(final byte[] buffer, final int startN,
final int len); DataChunk addValue(final Buffer buffer, final int startN,
final int len); DataChunk setValue(final String name); DataChunk setValue(final Header header); DataChunk getValue(String name); DataChunk getValue(final Header header); String getHeader(String name); String getHeader(final Header header); void removeHeader(String name); void removeHeader(final Header header); @SuppressWarnings("UnusedDeclaration") void removeHeader(final String name, final String str); @SuppressWarnings("UnusedDeclaration") void removeHeaderMatches(final String name, final String regex); void removeHeaderMatches(final Header header, final String regex); void setMaxNumHeaders(int maxNumHeaders); @SuppressWarnings("unused") int getMaxNumHeaders(); static final int MAX_NUM_HEADERS_UNBOUNDED; static final int MAX_NUM_HEADERS_DEFAULT; static final int DEFAULT_HEADER_SIZE; static DataChunk NOOP_CHUNK; } | @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 : result) { list.add(s); } Assert.assertArrayEquals(emptySet, list.toArray(new String[list.size()])); result = mimeHeaders.trailerValues("custom-before-2"); list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(emptySet, list.toArray(new String[list.size()])); result = mimeHeaders.trailerValues("custom-after"); list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedValuesSet1, list.toArray(new String[list.size()])); result = mimeHeaders.trailerValues("custom-after-2"); list = new ArrayList<>(); for (String s : result) { list.add(s); } Assert.assertArrayEquals(expectedValuesSet2, list.toArray(new String[list.size()])); } |
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); } return builder.toString(); } ApacheLogFormat(String format); ApacheLogFormat(TimeZone timeZone, String format); @Override String format(Response response, Date timeStamp, long responseNanos); String getFormat(); static final String COMMON_FORMAT; static final String COMBINED_FORMAT; static final String VHOST_COMMON_FORMAT; static final String VHOST_COMBINED_FORMAT; static final String REFERER_FORMAT; static final String AGENT_FORMAT; static final ApacheLogFormat COMMON; static final ApacheLogFormat COMBINED; static final ApacheLogFormat VHOST_COMMON; static final ApacheLogFormat VHOST_COMBINED; static final ApacheLogFormat REFERER; static final ApacheLogFormat AGENT; static final ApacheLogFormat COMMON_UTC; static final ApacheLogFormat COMBINED_UTC; static final ApacheLogFormat VHOST_COMMON_UTC; static final ApacheLogFormat VHOST_COMBINED_UTC; static final ApacheLogFormat REFERER_UTC; static final ApacheLogFormat AGENT_UTC; } | @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("remote-host - remote-user [2014/Jan/15:23:45:12 +0000] \"GET /test/path?testing=true HTTP/1.1\" 210 1234567 \"http: assertEquals("server-name remote-host - remote-user [2014/Jan/15:23:45:12 +0000] \"GET /test/path?testing=true HTTP/1.1\" 210 1234567", ApacheLogFormat.VHOST_COMMON_UTC.unsafeFormat(response, date, nanos)); assertEquals("server-name remote-host - remote-user [2014/Jan/15:23:45:12 +0000] \"GET /test/path?testing=true HTTP/1.1\" 210 1234567 \"http: assertEquals("http: assertEquals("Test-User-Agent", ApacheLogFormat.AGENT_UTC.unsafeFormat(response, date, nanos)); }
@Test public void testBasicFormatsEmptyResponse() { final Response response = mockEmptyResponse(); assertEquals(ApacheLogFormat.COMMON_UTC .unsafeFormat(response, date, nanos), "- - - [2014/Jan/15:23:45:12 +0000] \"- - -\" 000 -"); assertEquals(ApacheLogFormat.COMBINED_UTC .unsafeFormat(response, date, nanos), "- - - [2014/Jan/15:23:45:12 +0000] \"- - -\" 000 - \"\" \"\""); assertEquals(ApacheLogFormat.VHOST_COMMON_UTC .unsafeFormat(response, date, nanos), "- - - - [2014/Jan/15:23:45:12 +0000] \"- - -\" 000 -"); assertEquals(ApacheLogFormat.VHOST_COMBINED_UTC.unsafeFormat(response, date, nanos), "- - - - [2014/Jan/15:23:45:12 +0000] \"- - -\" 000 - \"\" \"\""); assertEquals(ApacheLogFormat.REFERER_UTC .unsafeFormat(response, date, nanos), " -> -"); assertEquals(ApacheLogFormat.AGENT_UTC .unsafeFormat(response, date, nanos), ""); }
@Test public void testEscapes() { final Response response = mockSimpleResponse(); assertEquals(new ApacheLogFormat("%%\\t\\b\\n\\r\\f\\%").unsafeFormat(response, date, nanos), "%\t\b\n\r\f%"); }
@Test public void testPatterns() { final Response response = mockSimpleResponse(); assertEquals(new ApacheLogFormat("%a").unsafeFormat(response, date, nanos), CLIENT_IP); assertEquals(new ApacheLogFormat("%A").unsafeFormat(response, date, nanos), SERVER_IP); assertEquals(new ApacheLogFormat("%b").unsafeFormat(response, date, nanos), Long.toString(CONTENT_LENGTH)); assertEquals(new ApacheLogFormat("%B").unsafeFormat(response, date, nanos), Long.toString(CONTENT_LENGTH)); assertEquals(new ApacheLogFormat("%{test-cookie}C").unsafeFormat(response, date, nanos), "Test-Cookie-Value"); assertEquals(new ApacheLogFormat("%D").unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%h").unsafeFormat(response, date, nanos), "remote-host"); assertEquals(new ApacheLogFormat("%{remote}h").unsafeFormat(response, date, nanos), "remote-host"); assertEquals(new ApacheLogFormat("%{local}h").unsafeFormat(response, date, nanos), "local-host"); assertEquals(new ApacheLogFormat("%H").unsafeFormat(response, date, nanos), "HTTP/1.1"); assertEquals(new ApacheLogFormat("%{User-Agent}i").unsafeFormat(response, date, nanos), "Test-User-Agent"); assertEquals(new ApacheLogFormat("%{Referer}i").unsafeFormat(response, date, nanos), "http: assertEquals(new ApacheLogFormat("%{Multi-Request}i").unsafeFormat(response, date, nanos), "request-value-1; request-value-2"); assertEquals(new ApacheLogFormat("%m").unsafeFormat(response, date, nanos), "GET"); assertEquals(new ApacheLogFormat("%{Content-Type}o").unsafeFormat(response, date, nanos), "x-test/test"); assertEquals(new ApacheLogFormat("%{Multi-Response}o").unsafeFormat(response, date, nanos), "response-value-1; response-value-2"); assertEquals(new ApacheLogFormat("%p").unsafeFormat(response, date, nanos), Integer.toString(SERVER_PORT)); assertEquals(new ApacheLogFormat("%{local}p").unsafeFormat(response, date, nanos), Integer.toString(SERVER_PORT)); assertEquals(new ApacheLogFormat("%{remote}p").unsafeFormat(response, date, nanos), Integer.toString(CLIENT_PORT)); assertEquals(new ApacheLogFormat("%q").unsafeFormat(response, date, nanos), "?testing=true"); assertEquals(new ApacheLogFormat("%r").unsafeFormat(response, date, nanos), "GET /test/path?testing=true HTTP/1.1"); assertEquals(new ApacheLogFormat("%s").unsafeFormat(response, date, nanos), Integer.toString(STATUS)); assertEquals(new ApacheLogFormat("%T") .unsafeFormat(response, date, nanos), Long.toString(SECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{s}T") .unsafeFormat(response, date, nanos), Long.toString(SECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{sec}T") .unsafeFormat(response, date, nanos), Long.toString(SECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{secs}T") .unsafeFormat(response, date, nanos), Long.toString(SECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{second}T") .unsafeFormat(response, date, nanos), Long.toString(SECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{seconds}T").unsafeFormat(response, date, nanos), Long.toString(SECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{m}T") .unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{milli}T") .unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{millis}T") .unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{millisec}T") .unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{millisecs}T") .unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{millisecond}T") .unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{milliseconds}T").unsafeFormat(response, date, nanos), Long.toString(MILLISECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{micro}T") .unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{micros}T") .unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{microsec}T") .unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{microsecs}T") .unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{microsecond}T") .unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{microseconds}T").unsafeFormat(response, date, nanos), Long.toString(MICROSECONDS.convert(nanos, NANOSECONDS))); assertEquals(new ApacheLogFormat("%{n}T") .unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%{nano}T") .unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%{nanos}T") .unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%{nanosec}T") .unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%{nanosecs}T") .unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%{nanosecond}T") .unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%{nanoseconds}T").unsafeFormat(response, date, nanos), Long.toString(nanos)); assertEquals(new ApacheLogFormat("%u").unsafeFormat(response, date, nanos), "remote-user"); assertEquals(new ApacheLogFormat("%U").unsafeFormat(response, date, nanos), "/test/path"); assertEquals(new ApacheLogFormat("%v").unsafeFormat(response, date, nanos), "server-name"); }
@Test public void testPatternsEmptyResponse() { final Response response = mockEmptyResponse(); assertEquals("remote-ip", "-", new ApacheLogFormat("%a").unsafeFormat(response, date, -1)); assertEquals("local-ip", "-", new ApacheLogFormat("%A").unsafeFormat(response, date, -1)); assertEquals("response bytes", "-", new ApacheLogFormat("%b").unsafeFormat(response, date, -1)); assertEquals("response bytes", "0", new ApacheLogFormat("%B").unsafeFormat(response, date, -1)); assertEquals("cookie", "", new ApacheLogFormat("%{test-cookie}C").unsafeFormat(response, date, -1)); assertEquals("response-time", "-", new ApacheLogFormat("%D").unsafeFormat(response, date, -1)); assertEquals("remote-host", "-", new ApacheLogFormat("%h").unsafeFormat(response, date, -1)); assertEquals("remote-host", "-", new ApacheLogFormat("%{remote}h").unsafeFormat(response, date, -1)); assertEquals("local-host", "-", new ApacheLogFormat("%{local}h").unsafeFormat(response, date, -1)); assertEquals("protocol", "-", new ApacheLogFormat("%H").unsafeFormat(response, date, -1)); assertEquals("request header", "", new ApacheLogFormat("%{header}i").unsafeFormat(response, date, -1)); assertEquals("method", "-", new ApacheLogFormat("%m").unsafeFormat(response, date, -1)); assertEquals("response header", "", new ApacheLogFormat("%{header}o").unsafeFormat(response, date, -1)); assertEquals("server port", "-", new ApacheLogFormat("%p").unsafeFormat(response, date, -1)); assertEquals("server port", "-", new ApacheLogFormat("%{local}p").unsafeFormat(response, date, -1)); assertEquals("client port" , "-", new ApacheLogFormat("%{remote}p").unsafeFormat(response, date, -1)); assertEquals("query", "", new ApacheLogFormat("%q").unsafeFormat(response, date, -1)); assertEquals("first line", "- - -", new ApacheLogFormat("%r").unsafeFormat(response, date, -1)); assertEquals("status", "000", new ApacheLogFormat("%s").unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{s}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{sec}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{secs}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{second}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{seconds}T").unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{m}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{milli}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{millis}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{millisec}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{millisecs}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{millisecond}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{milliseconds}T").unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{micro}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{micros}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{microsec}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{microsecs}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{microsecond}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{microseconds}T").unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{n}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{nano}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{nanos}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{nanosec}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{nanosecs}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{nanosecond}T") .unsafeFormat(response, date, -1)); assertEquals("response time", "-", new ApacheLogFormat("%{nanoseconds}T").unsafeFormat(response, date, -1)); assertEquals("remote-user", "-", new ApacheLogFormat("%u").unsafeFormat(response, date, -1)); assertEquals("request-uri", "-", new ApacheLogFormat("%U").unsafeFormat(response, date, -1)); assertEquals("server-name", "-", new ApacheLogFormat("%v").unsafeFormat(response, date, -1)); }
@Test public void testDates() { final TimeZone utc = TimeZone.getTimeZone("UTC"); final TimeZone jst = TimeZone.getTimeZone("JST"); final Response response = mockEmptyResponse(); assertEquals(new ApacheLogFormat(utc, "%t") .unsafeFormat(response, date, nanos), "[2014/Jan/15:23:45:12 +0000]"); assertEquals(new ApacheLogFormat(jst, "%t") .unsafeFormat(response, date, nanos), "[2014/Jan/16:08:45:12 +0900]"); assertEquals(new ApacheLogFormat(utc, "%{HH:mm:ss.SSS}t").unsafeFormat(response, date, nanos), "23:45:12.345"); assertEquals(new ApacheLogFormat(jst, "%{HH:mm:ss.SSS}t").unsafeFormat(response, date, nanos), "08:45:12.345"); assertEquals(new ApacheLogFormat(utc, "%{@@HH:mm:ss}t").unsafeFormat(response, date, nanos), "@23:45:12"); assertEquals(new ApacheLogFormat(jst, "%{@@HH:mm:ss}t").unsafeFormat(response, date, nanos), "@08:45:12"); assertEquals(new ApacheLogFormat(utc, "%{@PST}t").unsafeFormat(response, date, nanos), "[2014/Jan/15:15:45:12 -0800]"); assertEquals(new ApacheLogFormat(jst, "%{@PST}t").unsafeFormat(response, date, nanos), "[2014/Jan/15:15:45:12 -0800]"); assertEquals(new ApacheLogFormat(utc, "%{HH:mm:ss.SSS@PST}t").unsafeFormat(response, date, nanos), "15:45:12.345"); assertEquals(new ApacheLogFormat(jst, "%{HH:mm:ss.SSS@PST}t").unsafeFormat(response, date, nanos), "15:45:12.345"); assertEquals(new ApacheLogFormat(utc, "%{@@HH:mm:ss@PST}t").unsafeFormat(response, date, nanos), "@15:45:12"); assertEquals(new ApacheLogFormat(jst, "%{@@HH:mm:ss@PST}t").unsafeFormat(response, date, nanos), "@15:45:12"); } |
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(Response response, Date timeStamp, long responseNanos); String getFormat(); static final String COMMON_FORMAT; static final String COMBINED_FORMAT; static final String VHOST_COMMON_FORMAT; static final String VHOST_COMBINED_FORMAT; static final String REFERER_FORMAT; static final String AGENT_FORMAT; static final ApacheLogFormat COMMON; static final ApacheLogFormat COMBINED; static final ApacheLogFormat VHOST_COMMON; static final ApacheLogFormat VHOST_COMBINED; static final ApacheLogFormat REFERER; static final ApacheLogFormat AGENT; static final ApacheLogFormat COMMON_UTC; static final ApacheLogFormat COMBINED_UTC; static final ApacheLogFormat VHOST_COMMON_UTC; static final ApacheLogFormat VHOST_COMBINED_UTC; static final ApacheLogFormat REFERER_UTC; static final ApacheLogFormat AGENT_UTC; } | @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", "%{user-agent}i"); assertFormat("%m"); assertFormat("%{Content-Type}o", "%{content-type}o"); assertFormat("%p"); assertFormat("%{local}p", "%p"); assertFormat("%{remote}p"); assertFormat("%q"); assertFormat("%r", "%m %U%q %H"); assertFormat("%s"); assertFormat("%T", "%T"); assertFormat("%{s}T", "%T"); assertFormat("%{sec}T", "%T"); assertFormat("%{secs}T", "%T"); assertFormat("%{second}T", "%T"); assertFormat("%{seconds}T", "%T"); assertFormat("%{m}T", "%{m}T"); assertFormat("%{milli}T", "%{m}T"); assertFormat("%{millis}T", "%{m}T"); assertFormat("%{millisec}T", "%{m}T"); assertFormat("%{millisecs}T", "%{m}T"); assertFormat("%{millisecond}T", "%{m}T"); assertFormat("%{milliseconds}T", "%{m}T"); assertFormat("%{micro}T", "%D"); assertFormat("%{micros}T", "%D"); assertFormat("%{microsec}T", "%D"); assertFormat("%{microsecs}T", "%D"); assertFormat("%{microsecond}T", "%D"); assertFormat("%{microseconds}T", "%D"); assertFormat("%{n}T", "%{n}T"); assertFormat("%{nano}T", "%{n}T"); assertFormat("%{nanos}T", "%{n}T"); assertFormat("%{nanosec}T", "%{n}T"); assertFormat("%{nanosecs}T", "%{n}T"); assertFormat("%{nanosecond}T", "%{n}T"); assertFormat("%{nanoseconds}T", "%{n}T"); assertFormat("%u"); assertFormat("%U"); assertFormat("%v"); assertFormat("%t"); assertFormat("%{HH:mm:ss.SSS}t"); assertFormat("%{@@HH:mm:ss}t"); assertFormat("%{@PST}t"); assertFormat("%{HH:mm:ss.SSS@PST}t"); assertFormat("%{@@HH:mm:ss@PST}t"); } |
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) httpPacket, compressionConfig, aliases); } CompressionEncodingFilter(final CompressionConfig compressionConfig,
final String[] aliases); CompressionEncodingFilter(CompressionModeI compressionMode,
int compressionMinSize,
String[] compressibleMimeTypes,
String[] noCompressionUserAgents,
String[] aliases); CompressionEncodingFilter(CompressionModeI compressionMode,
int compressionMinSize,
String[] compressibleMimeTypes,
String[] noCompressionUserAgents,
String[] aliases,
boolean enableDecompression); @Override boolean applyEncoding(final HttpHeader httpPacket); @Override boolean applyDecoding(final HttpHeader httpPacket); } | @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(Protocol.HTTP_1_1).uri("/").build(), "gzip"); HttpResponsePacket response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).build(); assertTrue(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "foo, gzip;q=1.0, foo2"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).build(); assertTrue(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "foo, gzip; q=1.0, foo2"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).build(); assertTrue(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "foo, gzip;q=0, foo2"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).build(); assertFalse(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "foo, gzip; q=0, foo2"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).build(); assertFalse(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "compress; q=0.5, gzip;q=1.0"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).build(); assertTrue(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "foo, gzip;q=1.0, foo2"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).header(Header.ContentEncoding, "gzip").build(); assertFalse(filter.applyEncoding(response)); }
@Test public void testMinSizeSetting() throws Exception { final CompressionEncodingFilter filter = new CompressionEncodingFilter(CompressionMode.ON, 1024, new String[0], new String[0], new String[] {"gzip"}); HttpRequestPacket request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "compress;q=0.5, gzip;q=1.0"); HttpResponsePacket response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).contentLength(1023).build(); assertFalse(filter.applyEncoding(response)); request = setAcceptEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "compress;q=0.5, gzip;q=1.0"); response = HttpResponsePacket.builder(request).protocol(Protocol.HTTP_1_1).contentLength(1024).build(); assertTrue(filter.applyEncoding(response)); } |
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); } CompressionEncodingFilter(final CompressionConfig compressionConfig,
final String[] aliases); CompressionEncodingFilter(CompressionModeI compressionMode,
int compressionMinSize,
String[] compressibleMimeTypes,
String[] noCompressionUserAgents,
String[] aliases); CompressionEncodingFilter(CompressionModeI compressionMode,
int compressionMinSize,
String[] compressibleMimeTypes,
String[] noCompressionUserAgents,
String[] aliases,
boolean enableDecompression); @Override boolean applyEncoding(final HttpHeader httpPacket); @Override boolean applyDecoding(final HttpHeader httpPacket); } | @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).protocol(Protocol.HTTP_1_1).uri("/").build(), "gzip"); assertTrue(filter.applyDecoding(request)); request = setContentEncoding( HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(), "identity"); assertFalse(filter.applyDecoding(request)); request = HttpRequestPacket.builder().method(Method.GET).protocol(Protocol.HTTP_1_1).uri("/").build(); assertFalse(filter.applyDecoding(request)); } |
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 CompositeBuffer newBuffer(final MemoryManager memoryManager,
final Buffer[] buffers, final boolean isReadOnly); DisposeOrder disposeOrder(); CompositeBuffer disposeOrder(final DisposeOrder disposeOrder); abstract CompositeBuffer append(Buffer buffer); @Override abstract CompositeBuffer prepend(Buffer buffer); @Override abstract Object[] underlying(); abstract void removeAll(); abstract void allowInternalBuffersDispose(boolean allow); abstract boolean allowInternalBuffersDispose(); abstract int bulk(BulkOperation operation); abstract int bulk(BulkOperation operation, int position, int limit); abstract boolean replace(Buffer oldBuffer, Buffer newBuffer); } | @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, final Setter setter) { setter.set((byte) Character.toUpperCase(value)); return false; } }); assertEquals("HELLO WORLD", composite.toStringContent(ascii)); } |
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 numberOfPools,
final int growthFactor,
final int numberOfPoolSlices,
final float percentOfHeap,
final float percentPreallocated,
final boolean isDirect); @Override Buffer allocate(final int size); @Override Buffer allocateAtLeast(int size); @Override Buffer reallocate(final Buffer oldBuffer, final int newSize); @Override void release(final Buffer buffer); @Override boolean willAllocateDirect(final int size); @Override MonitoringConfig<MemoryProbe> getMonitoringConfig(); @Override Buffer wrap(final byte[] data); @Override Buffer wrap(byte[] data, int offset, int length); @Override Buffer wrap(final String s); @Override Buffer wrap(final String s, final Charset charset); @Override Buffer wrap(final ByteBuffer byteBuffer); static final int DEFAULT_BASE_BUFFER_SIZE; static final int DEFAULT_NUMBER_OF_POOLS; static final int DEFAULT_GROWTH_FACTOR; static final float DEFAULT_HEAP_USAGE_PERCENTAGE; static final float DEFAULT_PREALLOCATED_BUFFERS_PERCENTAGE; } | @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 * .105f); PooledMemoryManager mm = new PooledMemoryManager(); PooledMemoryManager.Pool[] pools = mm.getPools(); assertEquals(DEFAULT_NUMBER_OF_POOLS, pools.length); int bufSize = DEFAULT_BASE_BUFFER_SIZE; for (int i = 0, len = pools.length; i < len; i++) { assertEquals(bufSize, pools[i].getBufferSize()); bufSize <<= DEFAULT_GROWTH_FACTOR; } PooledMemoryManager.PoolSlice[] slices = pools[0].getSlices(); assertEquals(numProcessors, slices.length); assertEquals(slices[0].getMaxElementsCount(), slices[0].elementsCount()); long consumedMemory = 0; for (int i = 0, len = pools.length; i < len; i++) { consumedMemory += pools[i].size(); } assertTrue(consumedMemory + " >= " + totalMemory + " failed", consumedMemory >= totalMemory); assertTrue(consumedMemory + " <= " + upperBound + " failed", consumedMemory <= upperBound); }
@Test public void testCustomizedPoolInitialization() throws Exception { final float memoryPercentage = 0.05f; final int processors = Runtime.getRuntime().availableProcessors(); final long maxMemory = Runtime.getRuntime().maxMemory(); PooledMemoryManager mm = new PooledMemoryManager(2048, 1, 0, processors, memoryPercentage, 1.0f, isDirect); final long memoryPerPool = (long) (maxMemory * memoryPercentage); final long upperBound = (long) (maxMemory * 0.0505f); PooledMemoryManager.Pool[] pools = mm.getPools(); assertEquals(1, pools.length); assertTrue(pools[0].size() + " >= " + memoryPerPool + " failed", pools[0].size() >= memoryPerPool); assertTrue(pools[0].size() + " <= " + upperBound + " failed", pools[0].size() <= upperBound); assertEquals(2048, pools[0].getBufferSize()); final float preallocatedPercentage = 0.25f; mm = new PooledMemoryManager(2048, 1, 0, processors, memoryPercentage, preallocatedPercentage, isDirect); pools = mm.getPools(); final PoolSlice slice0 = pools[0].getSlices()[0]; assertEquals((int) (slice0.getMaxElementsCount() * preallocatedPercentage), slice0.elementsCount()); } |
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 (curBufSize >= newSize) { final PoolBuffer oldPoolBuffer = (PoolBuffer) oldBuffer; final Pool newPool = getPoolFor(newSize); if (newPool != oldPoolBuffer.owner().owner) { final int pos = Math.min(oldPoolBuffer.position(), newSize); final Buffer newPoolBuffer = newPool.allocate(); Buffers.setPositionLimit(oldPoolBuffer, 0, newSize); newPoolBuffer.put(oldPoolBuffer); Buffers.setPositionLimit(newPoolBuffer, pos, newSize); oldPoolBuffer.tryDispose(); return newPoolBuffer; } return oldPoolBuffer.limit(newSize); } else { final int pos = oldBuffer.position(); Buffers.setPositionLimit(oldBuffer, 0, curBufSize); if (newSize <= maxPooledBufferSize) { final Pool newPool = getPoolFor(newSize); final Buffer newPoolBuffer = newPool.allocate(); newPoolBuffer.put(oldBuffer); Buffers.setPositionLimit(newPoolBuffer, pos, newSize); oldBuffer.tryDispose(); return newPoolBuffer; } else { final CompositeBuffer cb = newCompositeBuffer(); cb.append(oldBuffer); allocateToCompositeBuffer(cb, newSize - curBufSize); Buffers.setPositionLimit(cb, pos, newSize); return cb; } } } else { assert oldBuffer.isComposite(); final CompositeBuffer oldCompositeBuffer = (CompositeBuffer) oldBuffer; if (curBufSize > newSize) { final int oldPos = oldCompositeBuffer.position(); Buffers.setPositionLimit(oldBuffer, newSize, newSize); oldCompositeBuffer.trim(); oldCompositeBuffer.position(Math.min(oldPos, newSize)); return oldCompositeBuffer; } else { return allocateToCompositeBuffer(oldCompositeBuffer, newSize - curBufSize); } } } PooledMemoryManager(); @SuppressWarnings("unused") PooledMemoryManager(final boolean isDirect); PooledMemoryManager(
final int baseBufferSize,
final int numberOfPools,
final int growthFactor,
final int numberOfPoolSlices,
final float percentOfHeap,
final float percentPreallocated,
final boolean isDirect); @Override Buffer allocate(final int size); @Override Buffer allocateAtLeast(int size); @Override Buffer reallocate(final Buffer oldBuffer, final int newSize); @Override void release(final Buffer buffer); @Override boolean willAllocateDirect(final int size); @Override MonitoringConfig<MemoryProbe> getMonitoringConfig(); @Override Buffer wrap(final byte[] data); @Override Buffer wrap(byte[] data, int offset, int length); @Override Buffer wrap(final String s); @Override Buffer wrap(final String s, final Charset charset); @Override Buffer wrap(final ByteBuffer byteBuffer); static final int DEFAULT_BASE_BUFFER_SIZE; static final int DEFAULT_NUMBER_OF_POOLS; static final int DEFAULT_GROWTH_FACTOR; static final float DEFAULT_HEAP_USAGE_PERCENTAGE; static final float DEFAULT_PREALLOCATED_BUFFERS_PERCENTAGE; } | @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()); assertTrue(b == nb); b.tryDispose(); nb.tryDispose(); b = mm.allocate(2048); nb = mm.reallocate(b, 4096); assertEquals(4096, nb.limit()); assertTrue(b == nb); b.tryDispose(); nb.tryDispose(); b = mm.allocate(2048); nb = mm.reallocate(b, 9999); assertEquals(9999, nb.limit()); assertTrue(b != nb); b.tryDispose(); nb.tryDispose(); b = mm.allocate(4096); nb = mm.reallocate(b, 4097); assertEquals(nb.limit(), 4097); assertTrue(b != nb); b.tryDispose(); nb.tryDispose(); } |
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(); @Override int remaining(); @Override boolean release(); @Override boolean isExternal(); } | @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 NextAction handleRead(FilterChainContext ctx) throws IOException { ctx.write(new FileTransfer(f)); return ctx.getStopAction(); } }); t.setProcessor(builder.build()); t.bind(PORT); t.start(); TCPNIOTransport client = TCPNIOTransportBuilder.newInstance().build(); FilterChainBuilder clientChain = FilterChainBuilder.stateless(); final SafeFutureImpl<File> future = SafeFutureImpl.create(); final File temp = File.createTempFile("grizzly-download-", ".tmp"); temp.deleteOnExit(); final FileOutputStream out = new FileOutputStream(temp); final AtomicInteger total = new AtomicInteger(0); clientChain.add(new TransportFilter()); clientChain.add(new BaseFilter() { @Override public NextAction handleConnect(FilterChainContext ctx) throws IOException { ctx.write(Buffers.wrap(MemoryManager.DEFAULT_MEMORY_MANAGER, ".")); return ctx.getStopAction(); } @Override public NextAction handleRead(FilterChainContext ctx) throws IOException { Buffer b = ctx.getMessage(); ByteBuffer bb = b.toByteBuffer(); total.addAndGet(b.remaining()); out.getChannel().write(bb); if (total.get() == f.length()) { future.result(temp); } return ctx.getStopAction(); } }); client.setProcessor(clientChain.build()); client.start(); client.connect("localhost", PORT); long start = System.currentTimeMillis(); BigInteger testSum = getMDSum(future.get(10, TimeUnit.SECONDS)); long stop = System.currentTimeMillis(); BigInteger controlSum = getMDSum(f); assertTrue(controlSum.equals(testSum)); System.out.println("File transfer completed in " + (stop - start) + " ms."); } |
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.dataManager().sync(); break; case SYNCED: onSavingsUpdated(); break; default: } } @Override List<T> getAll(); @Override void onResume(); @Override void addDataListeningObject(DataListening observer); @Override void deregister(DataListening observer); @Override void onPause(); @Override void update(Observable observable, Object o); } | @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.syncCalled()).isZero(); } |
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 testTransaction = new Transaction("someBank", "some bank id", booking); Filter component_under_test = new OneDayFilter(expectedDate); assertThat(component_under_test.shouldBeRemoved(testTransaction)).isTrue(); }
@Test public void teste_filter_withMatchingDay_shouldReturnStay() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date expectedDate = sdf.parse("11/07/2017"); Date bookingDate = sdf.parse("11/07/2017"); Booking booking = new Booking(); booking.setDate(bookingDate); Transaction testTransaction = new Transaction("someBank", "some bank id", booking); Filter component_under_test = new OneDayFilter(expectedDate); assertThat(component_under_test.shouldBeRemoved(testTransaction)).isFalse(); } |
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, Boolean> map); boolean hasItemsChecked(); boolean shouldBePresented(String bankAccountID); void update(Map<String, Boolean> map); @Override boolean shouldBeRemoved(Transaction t); } | @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() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test1", false); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.hasItemsChecked()).isFalse(); }
@Test public void teste_hasItemsChecked_withMapwithCheckedItem_shouldReturnTrue() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test1", true); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.hasItemsChecked()).isTrue(); } |
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); void update(Map<String, Boolean> map); @Override boolean shouldBeRemoved(Transaction t); } | @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_shouldBePresented_withKeyInMapButValueIsFalse_shouldReturnFalse() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test1", false); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.shouldBePresented("test1")).isFalse(); }
@Test public void teste_shouldBePresented_withWithKeyInMapAndValueTrue_shouldReturnTrue() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test1", true); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.shouldBePresented("test1")).isTrue(); } |
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 shouldBePresented(String bankAccountID); void update(Map<String, Boolean> map); @Override boolean shouldBeRemoved(Transaction t); } | @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))).isFalse(); }
@Test public void teste_shouldBeRemoved_withWithKeyInMapAndValueFalse_shouldReturnTrue() { HashMap<String, Boolean> data = new HashMap<>(); data.put("test1", false); ItemCheckedMap component_under_test = new ItemCheckedMap(data); assertThat(component_under_test.shouldBeRemoved(new Transaction(null, "test1", null))).isTrue(); }
@Test public void teste_shouldBeRemoved_withNoData_shouldReturnFalse() { ItemCheckedMap component_under_test = new ItemCheckedMap(new HashMap<String, Boolean>()); assertThat(component_under_test.shouldBeRemoved(new Transaction(null, "test1", null))).isFalse(); } |
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 addDataListeningObject(DataListening observer); @Override void deregister(DataListening observer); @Override void onPause(); @Override void update(Observable observable, Object o); } | @Test public void teste_addDataListening_shouldRegisterItselfOnDataManager() { StubbedDataManager dataManager = new StubbedDataManager(); FullfilledSupplier componenet_under_test = new FullfilledSupplier(dataManager); DummyDataListening dataListening = new DummyDataListening(); componenet_under_test.addDataListeningObject(dataListening); assertThat(dataManager.observers()).containsExactly(componenet_under_test); } |
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 getAmount(); double getAmountDelta(); Supplier<Transaction> getTransactionSuppllier(); } | @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 = 123.456; double amount1 = 500.00; double amount2 = -100.00; Booking booking1 = new Booking(new Date(), amount1); Transaction transaction1 = new Transaction("some name","some id",booking1); Booking booking2 = new Booking(new Date(), amount2); Transaction transaction2 = new Transaction("some name","some id",booking2); BankingDateInformation bankingDateInformation = new BankingDateInformation(amount, new StubbedBankTransactionSupplier(transaction1, transaction2)); assertThat(bankingDateInformation.getAmountDelta()).isEqualTo(amount1+amount2); } |
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_compare_firstDateLaterThenSecond_shouldReturnOne() throws Exception { SavingsComparator component_under_test = new SavingsComparator(); SavingsAccount earlyAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/16"), any()); SavingsAccount lateAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/17"), any()); assertThat(component_under_test.compare(lateAccount, earlyAccount)).isEqualTo(1); }
@Test public void teste_compare_firstDateBeforeThenSecond_shouldReturnMinusOne() throws Exception { SavingsComparator component_under_test = new SavingsComparator(); SavingsAccount earlyAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/16"), any()); SavingsAccount lateAccount = new SavingsAccount(123, "some anme", 10, 0, toDate("10/10/17"), any()); assertThat(component_under_test.compare(earlyAccount, lateAccount)).isEqualTo(-1); } |
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(final String userId); List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId); List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin); BankAccessBankingModel addBankAccess(final String userId, final BankAccessBankingModel bankAccess); } | @Test public void getAccessesBinderCalled() { DummyBankAccessEndpoint endpoint = mock(DummyBankAccessEndpoint.class); when(bankingApiBinder.getBankAccessEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.getBankAccesses("test"); } catch (BankingException ex) { fail("An Banking Exception was thrown! " + ex.getMessage()); } Mockito.verify(bankingApiBinder, times(1)).getBankAccessEndpoint(anyString()); } |
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<BankAccessBankingModel> getBankAccesses(final String userId); List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId); List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin); BankAccessBankingModel addBankAccess(final String userId, final BankAccessBankingModel bankAccess); } | @Test public void getAccountsBinderCalled() { DummyBankAccountEndpoint endpoint = mock(DummyBankAccountEndpoint.class); when(bankingApiBinder.getBankAccountEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.getBankAccounts("test", "test"); } catch (BankingException ex) { fail("An Banking Exception was thrown! " + ex.getMessage()); } Mockito.verify(bankingApiBinder, times(1)).getBankAccountEndpoint(anyString()); } |
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 BankingApiBinder binder); protected BankingApiFacade(); List<BankAccessBankingModel> getBankAccesses(final String userId); List<BankAccountBankingModel> getBankAccounts(final String userId, final String bankAccessId); List<BookingModel> syncBankAccount(final String userId, final String bankAccessId, final String bankAccountId, final String pin); BankAccessBankingModel addBankAccess(final String userId, final BankAccessBankingModel bankAccess); } | @Test public void syncAccountBinderCalled() { DummyBankAccountEndpoint endpoint = mock(DummyBankAccountEndpoint.class); when(bankingApiBinder.getBankAccountEndpoint(anyString())).thenReturn(endpoint); BankingApiFacade bankingApiFacade = new BankingApiFacade(bankingApiBinder); try { bankingApiFacade.syncBankAccount("test", "test", "test", "test"); } catch (BankingException ex) { fail("An Banking Exception was thrown! " + ex.getMessage()); } Mockito.verify(bankingApiBinder, times(1)).getBankAccountEndpoint(anyString()); } |
DummyBankAccountEndpoint implements BankAccountEndpoint { @Override public List<BankAccountBankingModel> getBankAccounts(String bankingAccessId) throws BankingException { if (!dummyBankAccessEndpoint.existsBankAccess(bankingAccessId)) { return new ArrayList<BankAccountBankingModel>(); } if (!bankAccountBankingModelRepository.existBankAccountsForAccessId(bankingAccessId)) { this.generateDummyBankAccountModels(bankingAccessId); } List<DummyBankAccountBankingModelEntity> allByAccessId = bankAccountBankingModelRepository.findAllByAccessId(bankingAccessId); List<BankAccountBankingModel> bankAccountBankingModelList = new ArrayList<>(); for (DummyBankAccountBankingModelEntity bankAccountBankingModelEntity : allByAccessId) { if (!bookingModelMap.containsKey(bankAccountBankingModelEntity.getId())) { generateDummyBookingModels(bankAccountBankingModelEntity.getId()); updateAccountBalance(bankAccountBankingModelEntity.getId()); } bankAccountBankingModelEntity.setBankAccountBalance(accountBalanceMap.get(bankAccountBankingModelEntity.getId())); bankAccountBankingModelList.add(bankAccountBankingModelEntity.transformIntoBankAccountBankingModel()); } return bankAccountBankingModelList; } @Autowired DummyBankAccountEndpoint(DummyBankAccountBankingModelRepository bankAccountBankingModelRepository, DummyBankAccessEndpointRepository bankAccessEndpointRepository, @Qualifier("dummy") DummyBankAccessEndpoint dummyBankAccessEndpoint); protected DummyBankAccountEndpoint(); @Override List<BankAccountBankingModel> getBankAccounts(String bankingAccessId); @Override List<BookingModel> syncBankAccount(String bankAccessId, String bankAccountId, String pin); } | @Test public void getBankAccountsAccountsExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpoint.existsBankAccess(anyString())).thenReturn(true); when(dummyBankAccountBankingModelRepository.existBankAccountsForAccessId(anyString())).thenReturn(true); when(dummyBankAccountBankingModelRepository.findAllByAccessId(anyString())).thenReturn(generateBankingAccounts()); DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint); List<BankAccountBankingModel> bankAccounts = dummyBankAccountEndpoint.getBankAccounts( "bankAccessId"); assertNotNull(bankAccounts); assertTrue(bankAccounts.size() == amountAccountsToGenerate); verify(dummyBankAccountBankingModelRepository, times(1)).findAllByAccessId(anyString()); }
@Test public void getBankAccountsAccountsNotExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpoint.existsBankAccess(anyString())).thenReturn(true); when(dummyBankAccountBankingModelRepository.existBankAccountsForAccessId(anyString())).thenReturn(false); DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint); List<BankAccountBankingModel> bankAccounts = dummyBankAccountEndpoint.getBankAccounts( "bankAccessId"); assertNotNull(bankAccounts); assertTrue(bankAccounts.size() >= 0); verify(dummyBankAccountBankingModelRepository, times(1)).findAllByAccessId(anyString()); verify(dummyBankAccountBankingModelRepository, atLeastOnce()).save(any(List.class)); } |
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 ServerCallStatusHandler handler); @Override void delete(final T element, final ServerCallStatusHandler handler); } | @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); } return bookingModelMap.get(bankAccountId); } @Autowired DummyBankAccountEndpoint(DummyBankAccountBankingModelRepository bankAccountBankingModelRepository, DummyBankAccessEndpointRepository bankAccessEndpointRepository, @Qualifier("dummy") DummyBankAccessEndpoint dummyBankAccessEndpoint); protected DummyBankAccountEndpoint(); @Override List<BankAccountBankingModel> getBankAccounts(String bankingAccessId); @Override List<BookingModel> syncBankAccount(String bankAccessId, String bankAccountId, String pin); } | @Test public void syncBankAccountsAccountsNotExist() throws Exception { String testUserId = "userId"; DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class); DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint); List<BookingModel> bookings = dummyBankAccountEndpoint.syncBankAccount( "bankAccessId", "bankAccountId", "pin"); assertNotNull(bookings); assertTrue(bookings.size() >= 0); } |
BankingApiBinder { BankAccountEndpoint getBankAccountEndpoint(final String userId) { return isTestUser(userId) ? dummyBankAccountEndpoint : httpBankAccountEndpoint; } @Autowired BankingApiBinder(final BankingApiConfiguration bankingApiConfiguration,
@Qualifier("default") final BankAccessEndpoint httpBankAccessEndpoint,
@Qualifier("dummy") final BankAccessEndpoint dummyBankAccessEndpoint,
@Qualifier("default") final BankAccountEndpoint httpBankAccountEndpoint,
@Qualifier("dummy") final BankAccountEndpoint dummyBankAccountEndpoint); protected BankingApiBinder(); } | @Test public void getBankAccountEndpointDummy() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, null, null, new HttpBankAccountEndpoint(null, null), new DummyBankAccountEndpoint(null, null, null)); BankAccountEndpoint endpoint = bankingApiBinder.getBankAccountEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof DummyBankAccountEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); }
@Test public void getBankAccountEndpointHttp() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, null, null, new HttpBankAccountEndpoint(null, null), new DummyBankAccountEndpoint(null, null, null)); BankAccountEndpoint endpoint = bankingApiBinder.getBankAccountEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof HttpBankAccountEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); } |
BankingApiBinder { BankAccessEndpoint getBankAccessEndpoint(final String userId) { return isTestUser(userId) ? dummyBankAccessEndpoint : httpBankAccessEndpoint; } @Autowired BankingApiBinder(final BankingApiConfiguration bankingApiConfiguration,
@Qualifier("default") final BankAccessEndpoint httpBankAccessEndpoint,
@Qualifier("dummy") final BankAccessEndpoint dummyBankAccessEndpoint,
@Qualifier("default") final BankAccountEndpoint httpBankAccountEndpoint,
@Qualifier("dummy") final BankAccountEndpoint dummyBankAccountEndpoint); protected BankingApiBinder(); } | @Test public void getBankAccessEndpointDummy() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, new HttpBankAccessEndpoint(null, null), new DummyBankAccessEndpoint(), null, null); BankAccessEndpoint endpoint = bankingApiBinder.getBankAccessEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof DummyBankAccessEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); }
@Test public void getBankAccessEndpointHttp() { String username = "[email protected]"; BankingApiBinder bankingApiBinder = new BankingApiBinder(this.bankingApiConfiguration, new HttpBankAccessEndpoint(null, null), new DummyBankAccessEndpoint(), null, null); BankAccessEndpoint endpoint = bankingApiBinder.getBankAccessEndpoint(username); Assert.assertNotNull(endpoint); Assert.assertTrue(endpoint instanceof HttpBankAccessEndpoint); verify(bankingApiConfiguration, times(1)).getTestUserNames(); } |
DummyBankAccessEndpoint implements BankAccessEndpoint { @Override public BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess) throws BankingException { BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setId("TestID" + number + "_" + System.nanoTime()); bankAccessBankingModel.setBankLogin(bankAccess.getBankLogin()); bankAccessBankingModel.setBankCode(bankAccess.getBankCode()); bankAccessBankingModel.setBankName("TestBank" + number); bankAccessBankingModel.setPin(null); bankAccessBankingModel.setPassportState("testPassportState"); bankAccessEndpointRepository.save(new DummyBankAccessBankingModelEntity(bankAccessBankingModel)); number++; return bankAccessBankingModel; } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBankingModel> getBankAccesses(); @Override BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess); boolean existsBankAccess(String bankAccessId); } | @Test public void addRepositoryCalled() throws Exception { String testUser = "user"; String testBankCode = "testCode"; String testBankLogin = "testLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setUserId(testUser); bankAccessBankingModel.setBankLogin(testBankLogin); bankAccessBankingModel.setBankCode(testBankCode); DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); DummyBankAccessEndpoint dummyBankAccessEndpoint = new DummyBankAccessEndpoint(dummyBankAccessEndpointRepository); dummyBankAccessEndpoint.addBankAccess(bankAccessBankingModel); verify(dummyBankAccessEndpointRepository, times(1)).save(any(DummyBankAccessBankingModelEntity.class)); } |
DummyBankAccessEndpoint implements BankAccessEndpoint { public boolean existsBankAccess(String bankAccessId) { return bankAccessEndpointRepository.exists(bankAccessId); } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBankingModel> getBankAccesses(); @Override BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess); boolean existsBankAccess(String bankAccessId); } | @Test public void existsRepositoryCalled() throws Exception { String testId = "test"; DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpointRepository.exists(anyString())).thenReturn(true); DummyBankAccessEndpoint dummyBankAccessEndpoint = new DummyBankAccessEndpoint(dummyBankAccessEndpointRepository); boolean existsPreChange = dummyBankAccessEndpoint.existsBankAccess(testId); verify(dummyBankAccessEndpointRepository, times(1)).exists(anyString()); } |
DummyBankAccessEndpoint implements BankAccessEndpoint { @Override public List<BankAccessBankingModel> getBankAccesses() throws BankingException { List<DummyBankAccessBankingModelEntity> dummyBankAccessBankingModelEntities = bankAccessEndpointRepository.findAll(); List<BankAccessBankingModel> bankAccessBankingModelList = new ArrayList<>(); for (DummyBankAccessBankingModelEntity dummyBankAccessBankingModelEntity : dummyBankAccessBankingModelEntities) { bankAccessBankingModelList.add(dummyBankAccessBankingModelEntity.transformToBankAccessBankingModel()); } return bankAccessBankingModelList; } DummyBankAccessEndpoint(DummyBankAccessEndpointRepository bankAccessEndpointRepository); DummyBankAccessEndpoint(); @Override List<BankAccessBankingModel> getBankAccesses(); @Override BankAccessBankingModel addBankAccess(BankAccessBankingModel bankAccess); boolean existsBankAccess(String bankAccessId); } | @Test public void getRepositoryCalled() throws Exception { String testId = "test"; DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class); when(dummyBankAccessEndpointRepository.findAll()).thenReturn(new ArrayList<DummyBankAccessBankingModelEntity>()); DummyBankAccessEndpoint dummyBankAccessEndpoint = new DummyBankAccessEndpoint(dummyBankAccessEndpointRepository); List<BankAccessBankingModel> bankAccessBankingModelList = dummyBankAccessEndpoint.getBankAccesses(); verify(dummyBankAccessEndpointRepository, times(1)).findAll(); } |
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.getLastName(); if (email == null || email.isEmpty()) { throw new ServletException("Username provided by authority must be specified"); } if (firstName == null || firstName.isEmpty()) { throw new ServletException("First name provided by authority must be specified"); } if (lastName == null || lastName.isEmpty()) { throw new ServletException("Family name provided by authority must be specified"); } try { authenticationController.register(new User(email, firstName, lastName)); logger.info("User " + email + " was registered!"); } catch (UserAlreadyExistsException e) { logger.info("User " + email + " was already registered!"); } catch (VirtualLedgerAuthenticationException e) { throw new ServletException(e); } chain.doFilter(request, response); } UserRegistrationFilter(KeycloakUtilizer keycloakUtilizer, AuthenticationController authenticationController); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); } | @Test(expected = ServletException.class) public void filterEmailNull() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer(null, "first", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); }
@Test(expected = ServletException.class) public void filterEmailEmpty() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("", "first", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); }
@Test(expected = ServletException.class) public void filterFirstNameNull() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", null, "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); }
@Test(expected = ServletException.class) public void filterFirstNameEmpty() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", "", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); }
@Test(expected = ServletException.class) public void filterLastNameNull() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", "first", null), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); }
@Test(expected = ServletException.class) public void filterLastNameEmpty() throws IOException, ServletException { UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", "first", null), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); }
@Test public void filterUserNotExists() throws IOException, ServletException, VirtualLedgerAuthenticationException, UserAlreadyExistsException { when(authenticationController.register(any(User.class))).thenReturn("test"); UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", "first", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(authenticationController, times(1)).register(any(User.class)); }
@Test public void filterUserExists() throws IOException, ServletException, VirtualLedgerAuthenticationException, UserAlreadyExistsException { when(authenticationController.register(any(User.class))).thenThrow(new UserAlreadyExistsException()); UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", "first", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(authenticationController, times(1)).register(any(User.class)); }
@Test(expected = ServletException.class) public void filterVirtualLedgerAuthenticationExceptionThrown() throws IOException, ServletException, VirtualLedgerAuthenticationException, UserAlreadyExistsException { when(authenticationController.register(any(User.class))).thenThrow(new VirtualLedgerAuthenticationException("mock")); UserRegistrationFilter userRegistrationFilter = new UserRegistrationFilter( setupKeycloakUtilizer("[email protected]", "first", "last"), authenticationController); userRegistrationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(authenticationController, times(1)).register(any(User.class)); } |
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 StringApiModel s) throws Exception { handler.onOk(); AbstractDataManager.this.sync(); } }; subscribe(handler, onNext, dataProvider.add(element)); } AbstractDataManager(DataProvider<T> dataProvider); @Override void sync(); @Override SyncStatus getSyncStatus(); @Override List<T> getAll(); @Override void add(final T element, final ServerCallStatusHandler handler); @Override void delete(final T element, final ServerCallStatusHandler handler); } | @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(savingsAccount, null); assertThat(dataProvider.accounts()).containsExactly(savingsAccount); } |
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! At least one was not formatted correctly!"); } if (this.userRepository.existsUserWithEmail(user.getEmail())) { throw new UserAlreadyExistsException(); } this.userRepository.save(user); return "You were registered! " + user.getEmail(); } @Autowired AuthenticationController(UserRepository userRepository); protected AuthenticationController(); String register(User user); } | @Test(expected = UserAlreadyExistsException.class) public void testRegisterWithExistingUserShouldThrowException() throws Exception { UserRepository userRepositoryMock = mock(UserRepository.class); when(userRepositoryMock.existsUserWithEmail(someEmail())).thenReturn(Boolean.TRUE); AuthenticationController componentUnderTest = new AuthenticationController(userRepositoryMock); User user = getValidUserCredential(); user.setEmail(someEmail()); componentUnderTest.register(user); }
@Test public void testRegisterWithValidUserShouldRegister() throws Exception { UserRepository userRepositoryMock = mock(UserRepository.class); AuthenticationController componentUnderTest = new AuthenticationController(userRepositoryMock); String result = componentUnderTest.register(getValidUserCredential()); assertThat(result).isEqualTo("You were registered! [email protected]"); } |
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.allCachedItems.size()); return new LinkedList<>(allCachedItems); } AbstractDataManager(DataProvider<T> dataProvider); @Override void sync(); @Override SyncStatus getSyncStatus(); @Override List<T> getAll(); @Override void add(final T element, final ServerCallStatusHandler handler); @Override void delete(final T element, final ServerCallStatusHandler handler); } | @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 bankingModel); List<BankAccess> createBankAccesses(List<BankAccessBankingModel> bankingModelList); } | @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(bankCode); bankAccessBankingModel.setBankLogin(bankLogin); bankAccessBankingModel.setId(accessId); BankAccess bankAccess = bankAccessFactory.createBankAccess(bankAccessBankingModel); Assert.assertNotNull(bankAccess); Assert.assertEquals(accessId, bankAccess.getId()); Assert.assertEquals(bankCode, bankAccess.getBankcode()); Assert.assertEquals(bankLogin, bankAccess.getBanklogin()); Assert.assertEquals(bankName, bankAccess.getName()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.