src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SnapshotPostProcessor { @VisibleForTesting static long updateVersionAndCheckConsistency(long localVersion, long newVersion, String errorMessage) { if (localVersion == -1) { return newVersion; } else { if (localVersion != newVersion) { throw new UnrecoverableStoreException(errorMessage, args -> args.add("localVersion", localVersion).add("newVersion", newVersion)); } } return localVersion; } SnapshotPostProcessor(BiFunction<SerializableSnapshot, String, SerializableSnapshot> processor); } | @Test public void shouldSucceedWhenInitializionSnapshotToAppModelVersion() { assertThat(updateVersionAndCheckConsistency(-1L, 5L, "shouldSucceed because the applicationVersion was not yet initialized")) .as("Whenever the Version is not initialized we can set it").isEqualTo(5L); }
@Test(expectedExceptions = UnrecoverableStoreException.class) public void shouldFailwhenUpdatingSnapshotToOtherVersion() { updateVersionAndCheckConsistency(8L, 88L, "should fail because the applicationModelVersion are not consistent between the stores"); } |
SnapshotPostProcessor { long getConsistentApplicationModelVersion() { long applicationModelVersion = 0; if (m_beforePostProcessingVersion > 0) { applicationModelVersion = m_beforePostProcessingVersion; } if (m_afterPostProcessingVersion > 0) { applicationModelVersion = m_afterPostProcessingVersion; } return applicationModelVersion; } SnapshotPostProcessor(BiFunction<SerializableSnapshot, String, SerializableSnapshot> processor); } | @Test public void shouldReturn0WhenNoApplicationVersionDefined() { SnapshotPostProcessor snapshotPostProcessor = new SnapshotPostProcessor((snapshot, storeName) -> snapshot); assertThat(snapshotPostProcessor.getConsistentApplicationModelVersion()).isEqualTo(0L); } |
SnapshotPostProcessor { SerializableSnapshot apply(String storeName, SerializableSnapshot serializableSnapshot) { m_beforePostProcessingVersion = updateVersionAndCheckConsistency(m_beforePostProcessingVersion, serializableSnapshot.getApplicationModelVersion(), "Snapshot serializable application model version differs among the stores"); SerializableSnapshot finalSnapshot = m_processor.apply(serializableSnapshot, storeName); m_afterPostProcessingVersion = updateVersionAndCheckConsistency(m_afterPostProcessingVersion, finalSnapshot.getApplicationModelVersion(), "Snapshot serializable application model version differs among the stores after post processing"); if (m_afterPostProcessingVersion < m_beforePostProcessingVersion) { throw new UnrecoverableStoreException("Application model version can not be decreased", args -> args.add("oldApplicationModelVersion", m_beforePostProcessingVersion) .add("newApplicationModelVersion", m_afterPostProcessingVersion)); } return finalSnapshot; } SnapshotPostProcessor(BiFunction<SerializableSnapshot, String, SerializableSnapshot> processor); } | @Test(expectedExceptions = UnrecoverableStoreException.class) public void shouldFailWhenValidatingPostProcessingUpdatingApplicationModelVersion() { SerializableSnapshot initialSnapshot = new SerializableSnapshot(); long initialSnapshotModelVersion = 10L; long finalSnapshotModelVersion = 9L; initialSnapshot.setApplicationModelVersion(initialSnapshotModelVersion); initialSnapshot.setSnapshotModelVersion(SNAPSHOT_MODEL_VERSION); BiFunction<SerializableSnapshot, String, SerializableSnapshot> updateTheApplicationModelVersion = (snapshot, storeName) -> { snapshot.setApplicationModelVersion(finalSnapshotModelVersion); return snapshot; }; SnapshotPostProcessor snapshotPostProcessor = new SnapshotPostProcessor(updateTheApplicationModelVersion); snapshotPostProcessor.apply("shouldSucceedWhenValidatingPostProcessingIdentity", initialSnapshot); } |
OAuthAsyncCompletionHandler extends AsyncCompletionHandler<T> { @Override public T onCompleted(com.ning.http.client.Response ningResponse) { try { final Map<String, String> headersMap = new HashMap<>(); for (Map.Entry<String, List<String>> header : ningResponse.getHeaders().entrySet()) { final StringBuilder value = new StringBuilder(); for (String str : header.getValue()) { value.append(str); } headersMap.put(header.getKey(), value.toString()); } final Response response = new Response(ningResponse.getStatusCode(), ningResponse.getStatusText(), headersMap, ningResponse.getResponseBodyAsStream()); @SuppressWarnings("unchecked") final T t = converter == null ? (T) response : converter.convert(response); if (callback != null) { callback.onCompleted(t); } return t; } catch (IOException | RuntimeException e) { onThrowable(e); return null; } } OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback<T> callback,
OAuthRequest.ResponseConverter<T> converter); @Override T onCompleted(com.ning.http.client.Response ningResponse); @Override void onThrowable(Throwable t); } | @Test public void shouldReleaseLatchOnSuccess() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER); final com.ning.http.client.Response response = new MockResponse(200, "ok", new FluentCaseInsensitiveStringsMap(), new byte[0]); handler.onCompleted(response); assertNotNull(callback.getResponse()); assertNull(callback.getThrowable()); assertEquals("All good", callback.getResponse()); }
@Test public void shouldReportOAuthException() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, OAUTH_EXCEPTION_RESPONSE_CONVERTER); final com.ning.http.client.Response response = new MockResponse(200, "ok", new FluentCaseInsensitiveStringsMap(), new byte[0]); handler.onCompleted(response); assertNull(callback.getResponse()); assertNotNull(callback.getThrowable()); assertTrue(callback.getThrowable() instanceof OAuthException); } |
HMACSha1SignatureService implements SignatureService { @Override public String getSignature(String baseString, String apiSecret, String tokenSecret) { try { Preconditions.checkEmptyString(baseString, "Base string cant be null or empty string"); Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string"); return doSign(baseString, OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret)); } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException | RuntimeException e) { throw new OAuthSignatureException(baseString, e); } } @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); } | @Test(expected = OAuthException.class) public void shouldThrowExceptionIfBaseStringIsEmpty() { service.getSignature(" ", "apiSecret", "tokenSecret"); }
@Test(expected = OAuthException.class) public void shouldThrowExceptionIfApiSecretIsNull() { service.getSignature("base string", null, "tokenSecret"); }
@Test(expected = OAuthException.class) public void shouldThrowExceptionIfApiSecretIsEmpty() { service.getSignature("base string", " ", "tokenSecret"); }
@Test public void shouldReturnSignature() { final String apiSecret = "api secret"; final String tokenSecret = "token secret"; final String baseString = "base string"; final String signature = "uGymw2KHOTWI699YEaoi5xyLT50="; assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); }
@Test(expected = OAuthException.class) public void shouldThrowExceptionIfBaseStringIsNull() { service.getSignature(null, "apiSecret", "tokenSecret"); } |
RSASha1SignatureService implements SignatureService { @Override public String getSignatureMethod() { return METHOD; } RSASha1SignatureService(PrivateKey privateKey); @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); } | @Test public void shouldReturnSignatureMethodString() { final String expected = "RSA-SHA1"; assertEquals(expected, service.getSignatureMethod()); } |
RSASha1SignatureService implements SignatureService { @Override public String getSignature(String baseString, String apiSecret, String tokenSecret) { try { final Signature signature = Signature.getInstance(RSA_SHA1); signature.initSign(privateKey); signature.update(baseString.getBytes(UTF8)); return BASE_64_ENCODER.encodeToString(signature.sign()); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | UnsupportedEncodingException | RuntimeException e) { throw new OAuthSignatureException(baseString, e); } } RSASha1SignatureService(PrivateKey privateKey); @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); } | @Test public void shouldReturnSignature() { final String apiSecret = "api secret"; final String tokenSecret = "token secret"; final String baseString = "base string"; final String signature = "LUNRzQAlpdNyM9mLXm96Va6g/qVNnEAb7p7K1KM0g8IopOFQJPoOO7cvppgt7w3QyhijWJnCmvqXaaIAGrqvd" + "yr3fIzBULh8D/iZQUNLMi08GCOA34P81XBvsc7A5uJjPDsGhJg2MzoVJ8nWJhU/lMMk4c92S1WGskeoDofRwpo="; assertEquals(signature, service.getSignature(baseString, apiSecret, tokenSecret)); } |
ParameterList { public String appendTo(String url) { Preconditions.checkNotNull(url, "Cannot append to null URL"); final String queryString = asFormUrlEncodedString(); if (queryString.equals(EMPTY_STRING)) { return url; } else { return url + (url.indexOf(QUERY_STRING_SEPARATOR) == -1 ? QUERY_STRING_SEPARATOR : PARAM_SEPARATOR) + queryString; } } ParameterList(); ParameterList(List<Parameter> params); ParameterList(Map<String, String> map); void add(String key, String value); String appendTo(String url); String asOauthBaseString(); String asFormUrlEncodedString(); void addAll(ParameterList other); void addQuerystring(String queryString); boolean contains(Parameter param); int size(); List<Parameter> getParams(); ParameterList sort(); } | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenAppendingNullMapToQuerystring() { params.appendTo(null); }
@Test public void shouldAppendNothingToQuerystringIfGivenEmptyMap() { final String url = "http: Assert.assertEquals(url, params.appendTo(url)); } |
Token implements Serializable { public String getParameter(String parameter) { String value = null; for (String str : rawResponse.split("&")) { if (str.startsWith(parameter + '=')) { final String[] part = str.split("="); if (part.length > 1) { value = part[1].trim(); } break; } } return value; } protected Token(String rawResponse); String getRawResponse(); String getParameter(String parameter); } | @Test public void shouldReturnUrlParam() { final Token actual = new OAuth1AccessToken("acccess", "secret", "user_id=3107154759&screen_name=someuser&empty=&="); assertEquals("someuser", actual.getParameter("screen_name")); assertEquals("3107154759", actual.getParameter("user_id")); assertEquals(null, actual.getParameter("empty")); assertEquals(null, actual.getParameter(null)); } |
OAuthRequest { public void addOAuthParameter(String key, String value) { oauthParameters.put(checkKey(key), value); } OAuthRequest(Verb verb, String url); void addOAuthParameter(String key, String value); Map<String, String> getOauthParameters(); void setRealm(String realm); String getRealm(); String getCompleteUrl(); void addHeader(String key, String value); void addBodyParameter(String key, String value); void addQuerystringParameter(String key, String value); void addParameter(String key, String value); MultipartPayload getMultipartPayload(); void setMultipartPayload(MultipartPayload multipartPayload); void initMultipartPayload(); void initMultipartPayload(String boundary); void initMultipartPayload(String subtype, String boundary); void initMultipartPayload(Map<String, String> headers); void initMultipartPayload(String boundary, Map<String, String> headers); void initMultipartPayload(String subtype, String boundary, Map<String, String> headers); @Deprecated void setByteArrayBodyPartPayloadInMultipartPayload(byte[] bodyPartPayload); @Deprecated void setByteArrayBodyPartPayloadInMultipartPayload(byte[] bodyPartPayload, String contentType); @Deprecated void setByteArrayBodyPartPayloadInMultipartPayload(byte[] bodyPartPayload, Map<String, String> headers); @Deprecated void addByteArrayBodyPartPayloadInMultipartPayload(byte[] bodyPartPayload); @Deprecated void addByteArrayBodyPartPayloadInMultipartPayload(byte[] bodyPartPayload, String contentType); @Deprecated void addByteArrayBodyPartPayloadInMultipartPayload(byte[] bodyPartPayload, Map<String, String> headers); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(byte[] fileContent); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(String contentType, byte[] fileContent); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(byte[] fileContent, String name); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(String contentType, byte[] fileContent, String name); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(byte[] fileContent, String name, String filename); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(String contentType, byte[] fileContent, String name,
String filename); @Deprecated void setFileByteArrayBodyPartPayloadInMultipartPayload(
FileByteArrayBodyPartPayload fileByteArrayBodyPartPayload); void setBodyPartPayloadInMultipartPayload(BodyPartPayload bodyPartPayload); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(byte[] fileContent); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(String contentType, byte[] fileContent); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(byte[] fileContent, String name); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(String contentType, byte[] fileContent, String name); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(byte[] fileContent, String name, String filename); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(String contentType, byte[] fileContent, String name,
String filename); @Deprecated void addFileByteArrayBodyPartPayloadInMultipartPayload(
FileByteArrayBodyPartPayload fileByteArrayBodyPartPayload); void addBodyPartPayloadInMultipartPayload(BodyPartPayload bodyPartPayload); void setPayload(String payload); void setPayload(byte[] payload); void setPayload(File payload); ParameterList getQueryStringParams(); ParameterList getBodyParams(); String getUrl(); String getSanitizedUrl(); String getStringPayload(); byte[] getByteArrayPayload(); File getFilePayload(); @Override String toString(); Verb getVerb(); Map<String, String> getHeaders(); String getCharset(); void setCharset(String charsetName); } | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfParameterIsNotOAuth() { request.addOAuthParameter("otherParam", "value"); } |
MultipartUtils { public static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final String preamble = multipartPayload.getPreamble(); if (preamble != null) { os.write((preamble + "\r\n").getBytes()); } final List<BodyPartPayload> bodyParts = multipartPayload.getBodyParts(); if (!bodyParts.isEmpty()) { final String boundary = multipartPayload.getBoundary(); final byte[] startBoundary = ("--" + boundary + "\r\n").getBytes(); for (BodyPartPayload bodyPart : bodyParts) { os.write(startBoundary); final Map<String, String> bodyPartHeaders = bodyPart.getHeaders(); if (bodyPartHeaders != null) { for (Map.Entry<String, String> header : bodyPartHeaders.entrySet()) { os.write((header.getKey() + ": " + header.getValue() + "\r\n").getBytes()); } } os.write("\r\n".getBytes()); if (bodyPart instanceof MultipartPayload) { getPayload((MultipartPayload) bodyPart).writeTo(os); } else if (bodyPart instanceof ByteArrayBodyPartPayload) { final ByteArrayBodyPartPayload byteArrayBodyPart = (ByteArrayBodyPartPayload) bodyPart; os.write(byteArrayBodyPart.getPayload(), byteArrayBodyPart.getOff(), byteArrayBodyPart.getLen()); } else { throw new AssertionError(bodyPart.getClass()); } os.write("\r\n".getBytes()); } os.write(("--" + boundary + "--").getBytes()); final String epilogue = multipartPayload.getEpilogue(); if (epilogue != null) { os.write(("\r\n" + epilogue).getBytes()); } } return os; } private MultipartUtils(); static void checkBoundarySyntax(String boundary); static String parseBoundaryFromHeader(String contentTypeHeader); static String generateDefaultBoundary(); static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload); } | @Test public void testEmptyMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload(); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKey()) .append(": ") .append(header.getValue()) .append("\r\n"); } assertEquals("Content-Type: multipart/form-data; boundary=\"" + mP.getBoundary() + "\"\r\n", headersString.toString()); assertEquals("", MultipartUtils.getPayload(mP).toString()); }
@Test public void testSimpleMultipartPayload() throws IOException { final Map<String, String> headers = new LinkedHashMap<>(); headers.put("X-Header", "X-Value"); headers.put("Content-Disposition", "Content-Disposition-Value"); final MultipartPayload mP = new MultipartPayload("mixed", "simple boundary", headers); mP.setPreamble("This is the preamble. It is to be ignored, though it\n" + "is a handy place for composition agents to include an\n" + "explanatory note to non-MIME conformant readers."); mP.addBodyPart(new ByteArrayBodyPartPayload(("This is implicitly typed plain US-ASCII text.\n" + "It does NOT end with a linebreak.").getBytes())); final ByteArrayBodyPartPayload bP = new ByteArrayBodyPartPayload( ("This is explicitly typed plain US-ASCII text.\n" + "It DOES end with a linebreak.\n").getBytes(), Collections.singletonMap(HttpClient.CONTENT_TYPE, "text/plain; charset=us-ascii")); mP.addBodyPart(bP); mP.setEpilogue("This is the epilogue. It is also to be ignored."); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKey()) .append(": ") .append(header.getValue()) .append("\r\n"); } assertEquals("X-Header: X-Value\r\n" + "Content-Disposition: Content-Disposition-Value\r\n" + "Content-Type: multipart/mixed; boundary=\"simple boundary\"\r\n", headersString.toString()); assertEquals("This is the preamble. It is to be ignored, though it\n" + "is a handy place for composition agents to include an\n" + "explanatory note to non-MIME conformant readers." + "\r\n--simple boundary\r\n" + "\r\n" + "This is implicitly typed plain US-ASCII text.\n" + "It does NOT end with a linebreak." + "\r\n--simple boundary\r\n" + "Content-Type: text/plain; charset=us-ascii\r\n" + "\r\n" + "This is explicitly typed plain US-ASCII text.\n" + "It DOES end with a linebreak.\n" + "\r\n--simple boundary--" + "\r\nThis is the epilogue. It is also to be ignored.", MultipartUtils.getPayload(mP).toString()); }
@Test public void testCRLFMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload("simple-boundary"); mP.addBodyPart(new ByteArrayBodyPartPayload("It does NOT end with a linebreak.".getBytes())); mP.addBodyPart(new ByteArrayBodyPartPayload("It does end with a \\r linebreak.\r".getBytes())); mP.addBodyPart(new ByteArrayBodyPartPayload("It does end with a \\n linebreak.\n".getBytes())); mP.addBodyPart(new ByteArrayBodyPartPayload("It does end with a \\r\\n linebreak.\r\n".getBytes())); mP.addBodyPart(new ByteArrayBodyPartPayload("the last one".getBytes())); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKey()) .append(": ") .append(header.getValue()) .append("\r\n"); } assertEquals("Content-Type: multipart/form-data; boundary=\"simple-boundary\"\r\n", headersString.toString()); assertEquals("--simple-boundary\r\n" + "\r\n" + "It does NOT end with a linebreak." + "\r\n--simple-boundary\r\n" + "\r\n" + "It does end with a \\r linebreak.\r" + "\r\n--simple-boundary\r\n" + "\r\n" + "It does end with a \\n linebreak.\n" + "\r\n--simple-boundary\r\n" + "\r\n" + "It does end with a \\r\\n linebreak.\r\n" + "\r\n--simple-boundary\r\n" + "\r\n" + "the last one" + "\r\n--simple-boundary--", MultipartUtils.getPayload(mP).toString()); }
@Test public void testFileByteArrayBodyPartPayloadMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload("testFileByteArrayBodyPartPayloadMultipartPayload boundary"); mP.addBodyPart(new FileByteArrayBodyPartPayload("fileContent".getBytes(), "name", "filename.ext")); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKey()) .append(": ") .append(header.getValue()) .append("\r\n"); } assertEquals("Content-Type: multipart/form-data; " + "boundary=\"testFileByteArrayBodyPartPayloadMultipartPayload boundary\"\r\n", headersString.toString()); assertEquals("--testFileByteArrayBodyPartPayloadMultipartPayload boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"filename.ext\"\r\n" + "\r\n" + "fileContent" + "\r\n--testFileByteArrayBodyPartPayloadMultipartPayload boundary--", MultipartUtils.getPayload(mP).toString()); }
@Test public void testComplexMultipartPayload() throws IOException { final MultipartPayload mP = new MultipartPayload("mixed", "unique-boundary-1"); mP.setPreamble("This is the preamble area of a multipart message.\n" + "Mail readers that understand multipart format\n" + "should ignore this preamble.\n" + "\n" + "If you are reading this text, you might want to\n" + "consider changing to a mail reader that understands\n" + "how to properly display multipart messages.\n"); mP.addBodyPart(new ByteArrayBodyPartPayload("... Some text appears here ...".getBytes())); mP.addBodyPart(new ByteArrayBodyPartPayload(("This could have been part of the previous part, but\n" + "illustrates explicit versus implicit typing of body\n" + "parts.\n").getBytes(), "text/plain; charset=US-ASCII")); final MultipartPayload innerMP = new MultipartPayload("parallel", "unique-boundary-2"); mP.addBodyPart(innerMP); final Map<String, String> audioHeaders = new LinkedHashMap<>(); audioHeaders.put("Content-Type", "audio/basic"); audioHeaders.put("Content-Transfer-Encoding", "base64"); innerMP.addBodyPart(new ByteArrayBodyPartPayload(("... base64-encoded 8000 Hz single-channel\n" + " mu-law-format audio data goes here ...").getBytes(), audioHeaders)); final Map<String, String> imageHeaders = new LinkedHashMap<>(); imageHeaders.put("Content-Type", "image/jpeg"); imageHeaders.put("Content-Transfer-Encoding", "base64"); innerMP.addBodyPart(new ByteArrayBodyPartPayload("... base64-encoded image data goes here ...".getBytes(), imageHeaders)); mP.addBodyPart(new ByteArrayBodyPartPayload(("This is <bold><italic>enriched.</italic></bold>\n" + "<smaller>as defined in RFC 1896</smaller>\n" + "\n" + "Isn't it\n" + "<bigger><bigger>cool?</bigger></bigger>\n").getBytes(), "text/enriched")); mP.addBodyPart(new ByteArrayBodyPartPayload(("From: (mailbox in US-ASCII)\n" + "To: (address in US-ASCII)\n" + "Subject: (subject in US-ASCII)\n" + "Content-Type: Text/plain; charset=ISO-8859-1\n" + "Content-Transfer-Encoding: Quoted-printable\n" + "\n" + "... Additional text in ISO-8859-1 goes here ...\n").getBytes(), "message/rfc822")); final StringBuilder headersString = new StringBuilder(); for (Map.Entry<String, String> header : mP.getHeaders().entrySet()) { headersString.append(header.getKey()) .append(": ") .append(header.getValue()) .append("\r\n"); } assertEquals("Content-Type: multipart/mixed; boundary=\"unique-boundary-1\"\r\n", headersString.toString()); assertEquals("This is the preamble area of a multipart message.\n" + "Mail readers that understand multipart format\n" + "should ignore this preamble.\n" + "\n" + "If you are reading this text, you might want to\n" + "consider changing to a mail reader that understands\n" + "how to properly display multipart messages.\n" + "\r\n--unique-boundary-1\r\n" + "\r\n" + "... Some text appears here ..." + "\r\n--unique-boundary-1\r\n" + "Content-Type: text/plain; charset=US-ASCII\r\n" + "\r\n" + "This could have been part of the previous part, but\n" + "illustrates explicit versus implicit typing of body\n" + "parts.\n" + "\r\n--unique-boundary-1\r\n" + "Content-Type: multipart/parallel; boundary=\"unique-boundary-2\"\r\n" + "\r\n--unique-boundary-2\r\n" + "Content-Type: audio/basic\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + "... base64-encoded 8000 Hz single-channel\n" + " mu-law-format audio data goes here ..." + "\r\n--unique-boundary-2\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + "... base64-encoded image data goes here ..." + "\r\n--unique-boundary-2--" + "\r\n--unique-boundary-1\r\n" + "Content-Type: text/enriched\r\n" + "\r\n" + "This is <bold><italic>enriched.</italic></bold>\n" + "<smaller>as defined in RFC 1896</smaller>\n" + "\n" + "Isn't it\n" + "<bigger><bigger>cool?</bigger></bigger>\n" + "\r\n--unique-boundary-1\r\n" + "Content-Type: message/rfc822\r\n" + "\r\n" + "From: (mailbox in US-ASCII)\n" + "To: (address in US-ASCII)\n" + "Subject: (subject in US-ASCII)\n" + "Content-Type: Text/plain; charset=ISO-8859-1\n" + "Content-Transfer-Encoding: Quoted-printable\n" + "\n" + "... Additional text in ISO-8859-1 goes here ...\n" + "\r\n--unique-boundary-1--", MultipartUtils.getPayload(mP).toString()); } |
MultipartUtils { public static String parseBoundaryFromHeader(String contentTypeHeader) { if (contentTypeHeader == null) { return null; } final Matcher matcher = BOUNDARY_FROM_HEADER_REGEXP.matcher(contentTypeHeader); return matcher.find() ? matcher.group(1) : null; } private MultipartUtils(); static void checkBoundarySyntax(String boundary); static String parseBoundaryFromHeader(String contentTypeHeader); static String generateDefaultBoundary(); static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload); } | @Test public void testParseBoundaryFromHeader() { assertNull(MultipartUtils.parseBoundaryFromHeader(null)); assertEquals("0aA'()+_,-./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"0aA'()+_,-./:=?\"")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"0aA'()+_, -./:=?\"")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"0aA'()+_, -./:=? \"")); assertEquals("0aA'()+_,-./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=0aA'()+_,-./:=?")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=0aA'()+_, -./:=?")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=0aA'()+_, -./:=? ")); assertEquals(" 0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary= 0aA'()+_, -./:=?")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundar=0aA'()+_, -./:=? ")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; ")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype;")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=")); assertEquals("0aA'()+_,", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=0aA'()+_,; -./:=? ")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"0aA'()+_, -./:=?")); assertEquals("0aA'()+_, -./:=?", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=0aA'()+_, -./:=?\"")); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; " + "boundary=1234567890123456789012345678901234567890123456789012345678901234567890")); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890", MultipartUtils.parseBoundaryFromHeader("multipart/subtype; " + "boundary=12345678901234567890123456789012345678901234567890123456789012345678901")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"\"")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=;123")); assertNull(MultipartUtils.parseBoundaryFromHeader("multipart/subtype; boundary=\"\"123")); } |
MultipartUtils { public static void checkBoundarySyntax(String boundary) { if (boundary == null || !BOUNDARY_REGEXP.matcher(boundary).matches()) { throw new IllegalArgumentException("{'boundary'='" + boundary + "'} has invalid syntax. Should be '" + BOUNDARY_PATTERN + "'."); } } private MultipartUtils(); static void checkBoundarySyntax(String boundary); static String parseBoundaryFromHeader(String contentTypeHeader); static String generateDefaultBoundary(); static ByteArrayOutputStream getPayload(MultipartPayload multipartPayload); } | @Test public void testValidCheckBoundarySyntax() { MultipartUtils.checkBoundarySyntax("0aA'()+_,-./:=?"); MultipartUtils.checkBoundarySyntax("0aA'()+_,- ./:=?"); MultipartUtils.checkBoundarySyntax(" 0aA'()+_,-./:=?"); MultipartUtils.checkBoundarySyntax("1234567890123456789012345678901234567890123456789012345678901234567890"); } |
Preconditions { public static void checkNotNull(Object object, String errorMsg) { check(object != null, errorMsg); } static void checkNotNull(Object object, String errorMsg); static void checkEmptyString(String string, String errorMsg); static boolean hasText(String str); } | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForNullObjects() { Preconditions.checkNotNull(null, ERROR_MSG); } |
Preconditions { public static void checkEmptyString(String string, String errorMsg) { check(hasText(string), errorMsg); } static void checkNotNull(Object object, String errorMsg); static void checkEmptyString(String string, String errorMsg); static boolean hasText(String str); } | @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForNullStrings() { Preconditions.checkEmptyString(null, ERROR_MSG); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForEmptyStrings() { Preconditions.checkEmptyString("", ERROR_MSG); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForSpacesOnlyStrings() { Preconditions.checkEmptyString(" ", ERROR_MSG); } |
FitBitJsonTokenExtractor extends OAuth2AccessTokenJsonExtractor { @Override public void generateError(String rawResponse) throws IOException { final JsonNode errorNode = OAuth2AccessTokenJsonExtractor.OBJECT_MAPPER.readTree(rawResponse) .get("errors").get(0); OAuth2Error errorCode; try { errorCode = OAuth2Error.parseFrom(extractRequiredParameter(errorNode, "errorType", rawResponse).asText()); } catch (IllegalArgumentException iaE) { errorCode = null; } throw new OAuth2AccessTokenErrorResponse(errorCode, errorNode.get("message").asText(), null, rawResponse); } protected FitBitJsonTokenExtractor(); static FitBitJsonTokenExtractor instance(); @Override void generateError(String rawResponse); } | @Test public void testErrorExtraction() throws IOException { final FitBitJsonTokenExtractor extractor = new FitBitJsonTokenExtractor(); final OAuth2AccessTokenErrorResponse thrown = assertThrows(OAuth2AccessTokenErrorResponse.class, new ThrowingRunnable() { @Override public void run() throws Throwable { extractor.generateError(ERROR_JSON); } }); assertSame(OAuth2Error.INVALID_GRANT, thrown.getError()); assertEquals(ERROR_DESCRIPTION, thrown.getErrorDescription()); } |
OAuthEncoder { public static String encode(String plain) { Preconditions.checkNotNull(plain, "Cannot encode null object"); String encoded; try { encoded = URLEncoder.encode(plain, CHARSET); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Charset not found while encoding string: " + CHARSET, uee); } for (Map.Entry<String, String> rule : ENCODING_RULES.entrySet()) { encoded = applyRule(encoded, rule.getKey(), rule.getValue()); } return encoded; } static String encode(String plain); static String decode(String encoded); } | @Test public void shouldPercentEncodeString() { final String plain = "this is a test &^"; final String encoded = "this%20is%20a%20test%20%26%5E"; assertEquals(encoded, OAuthEncoder.encode(plain)); }
@Test public void shouldNotPercentEncodeReservedCharacters() { final String plain = "abcde123456-._~"; final String encoded = plain; assertEquals(encoded, OAuthEncoder.encode(plain)); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfStringToEncodeIsNull() { OAuthEncoder.encode(null); }
@Test public void shouldPercentEncodeCorrectlyTwitterCodingExamples() { final String[] sources = {"Ladies + Gentlemen", "An encoded string!", "Dogs, Cats & Mice"}; final String[] encoded = {"Ladies%20%2B%20Gentlemen", "An%20encoded%20string%21", "Dogs%2C%20Cats%20%26%20Mice"}; for (int i = 0; i < sources.length; i++) { assertEquals(encoded[i], OAuthEncoder.encode(sources[i])); } } |
OAuthEncoder { public static String decode(String encoded) { Preconditions.checkNotNull(encoded, "Cannot decode null object"); try { return URLDecoder.decode(encoded, CHARSET); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Charset not found while decoding string: " + CHARSET, uee); } } static String encode(String plain); static String decode(String encoded); } | @Test public void shouldFormURLDecodeString() { final String encoded = "this+is+a+test+%26%5E"; final String plain = "this is a test &^"; assertEquals(plain, OAuthEncoder.decode(encoded)); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfStringToDecodeIsNull() { OAuthEncoder.decode(null); } |
StreamUtils { public static String getStreamContents(InputStream is) throws IOException { Preconditions.checkNotNull(is, "Cannot get String from a null object"); final char[] buffer = new char[0x10000]; final StringBuilder out = new StringBuilder(); try (Reader in = new InputStreamReader(is, "UTF-8")) { int read; do { read = in.read(buffer, 0, buffer.length); if (read > 0) { out.append(buffer, 0, read); } } while (read >= 0); } return out.toString(); } static String getStreamContents(InputStream is); static String getGzipStreamContents(InputStream is); } | @Test public void shouldCorrectlyDecodeAStream() throws IOException { final String value = "expected"; final InputStream is = new ByteArrayInputStream(value.getBytes()); final String decoded = StreamUtils.getStreamContents(is); assertEquals("expected", decoded); }
@Test(expected = IllegalArgumentException.class) public void shouldFailForNullParameter() throws IOException { StreamUtils.getStreamContents(null); fail("Must throw exception before getting here"); }
@Test(expected = IOException.class) public void shouldFailWithBrokenStream() throws IOException { StreamUtils.getStreamContents(ALLWAYS_ERROR_INPUT_STREAM); fail("Must throw exception before getting here"); } |
OAuth2AccessTokenExtractor implements TokenExtractor<OAuth2AccessToken> { @Override public OAuth2AccessToken extract(Response response) throws IOException { if (response.getCode() != 200) { throw new OAuthException("Response code is not 200 but '" + response.getCode() + '\''); } final String body = response.getBody(); Preconditions.checkEmptyString(body, "Response body is incorrect. Can't extract a token from an empty string"); final String accessToken = extractParameter(body, ACCESS_TOKEN_REGEX_PATTERN, true); final String tokenType = extractParameter(body, TOKEN_TYPE_REGEX_PATTERN, false); final String expiresInString = extractParameter(body, EXPIRES_IN_REGEX_PATTERN, false); Integer expiresIn; try { expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString); } catch (NumberFormatException nfe) { expiresIn = null; } final String refreshToken = extractParameter(body, REFRESH_TOKEN_REGEX_PATTERN, false); final String scope = extractParameter(body, SCOPE_REGEX_PATTERN, false); return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, body); } protected OAuth2AccessTokenExtractor(); static OAuth2AccessTokenExtractor instance(); @Override OAuth2AccessToken extract(Response response); } | @Test public void shouldExtractTokenFromOAuthStandardResponse() throws IOException { final String responseBody = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE"; final OAuth2AccessToken extracted; try (Response response = ok(responseBody)) { extracted = extractor.extract(response); } assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", extracted.getAccessToken()); }
@Test public void shouldExtractTokenFromResponseWithExpiresParam() throws IOException { final String responseBody = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108"; final OAuth2AccessToken extracted; try (Response response = ok(responseBody)) { extracted = extractor.extract(response); } assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", extracted.getAccessToken()); assertEquals(Integer.valueOf(5108), extracted.getExpiresIn()); }
@Test public void shouldExtractTokenFromResponseWithExpiresAndRefreshParam() throws IOException { final String responseBody = "access_token=166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159" + "|RsXNdKrpxg8L6QNLWcs2TVTmcaE&expires_in=5108&token_type=bearer&refresh_token=166942940015970"; final OAuth2AccessToken extracted; try (Response response = ok(responseBody)) { extracted = extractor.extract(response); } assertEquals("166942940015970|2.2ltzWXYNDjCtg5ZDVVJJeg__.3600.1295816400-548517159|RsXNdKrpxg8L6QNLWcs2TVTmcaE", extracted.getAccessToken()); assertEquals(Integer.valueOf(5108), extracted.getExpiresIn()); assertEquals("bearer", extracted.getTokenType()); assertEquals("166942940015970", extracted.getRefreshToken()); }
@Test public void shouldExtractTokenFromResponseWithManyParameters() throws IOException { final String responseBody = "access_token=foo1234&other_stuff=yeah_we_have_this_too&number=42"; final OAuth2AccessToken extracted; try (Response response = ok(responseBody)) { extracted = extractor.extract(response); } assertEquals("foo1234", extracted.getAccessToken()); }
@Test(expected = OAuthException.class) public void shouldThrowExceptionIfErrorResponse() throws IOException { final String responseBody = ""; try (Response response = error(responseBody)) { extractor.extract(response); } }
@Test(expected = OAuthException.class) public void shouldThrowExceptionIfTokenIsAbsent() throws IOException { final String responseBody = "&expires=5108"; try (Response response = ok(responseBody)) { extractor.extract(response); } }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfResponseIsNull() throws IOException { try (Response response = ok(null)) { extractor.extract(response); } }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfResponseIsEmptyString() throws IOException { final String responseBody = ""; try (Response response = ok(responseBody)) { extractor.extract(response); } } |
OAuthAsyncCompletionHandler implements Callback { @Override public void onResponse(Call call, okhttp3.Response okHttpResponse) { try { final Response response = OkHttpHttpClient.convertResponse(okHttpResponse); try { @SuppressWarnings("unchecked") final T t = converter == null ? (T) response : converter.convert(response); okHttpFuture.setResult(t); if (callback != null) { callback.onCompleted(t); } } catch (IOException | RuntimeException e) { okHttpFuture.setException(e); if (callback != null) { callback.onThrowable(e); } } } finally { okHttpFuture.finish(); } } OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback<T> callback, OAuthRequest.ResponseConverter<T> converter,
OkHttpFuture<T> okHttpFuture); @Override void onFailure(Call call, IOException exception); @Override void onResponse(Call call, okhttp3.Response okHttpResponse); } | @Test public void shouldReleaseLatchOnSuccess() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER, future); call.enqueue(handler); final Request request = new Request.Builder().url("http: final okhttp3.Response response = new okhttp3.Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(200) .message("ok") .body(ResponseBody.create(new byte[0], MediaType.get("text/plain"))) .build(); handler.onResponse(call, response); assertNotNull(callback.getResponse()); assertNull(callback.getThrowable()); assertEquals("All good", future.get()); }
@Test public void shouldReleaseLatchOnIOException() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, EXCEPTION_RESPONSE_CONVERTER, future); call.enqueue(handler); final Request request = new Request.Builder().url("http: final okhttp3.Response response = new okhttp3.Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(200) .message("ok") .body(ResponseBody.create(new byte[0], MediaType.get("text/plain"))) .build(); handler.onResponse(call, response); assertNull(callback.getResponse()); assertNotNull(callback.getThrowable()); assertTrue(callback.getThrowable() instanceof IOException); try { future.get(); fail(); } catch (ExecutionException expected) { } }
@Test public void shouldReportOAuthException() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, OAUTH_EXCEPTION_RESPONSE_CONVERTER, future); call.enqueue(handler); final Request request = new Request.Builder().url("http: final okhttp3.Response response = new okhttp3.Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(200) .message("ok") .body(ResponseBody.create(new byte[0], MediaType.get("text/plain"))) .build(); handler.onResponse(call, response); assertNull(callback.getResponse()); assertNotNull(callback.getThrowable()); assertTrue(callback.getThrowable() instanceof OAuthException); try { future.get(); fail(); } catch (ExecutionException expected) { } } |
OAuth2AccessTokenJsonExtractor implements TokenExtractor<OAuth2AccessToken> { @Override public OAuth2AccessToken extract(Response response) throws IOException { final String body = response.getBody(); Preconditions.checkEmptyString(body, "Response body is incorrect. Can't extract a token from an empty string"); if (response.getCode() != 200) { generateError(body); } return createToken(body); } protected OAuth2AccessTokenJsonExtractor(); static OAuth2AccessTokenJsonExtractor instance(); @Override OAuth2AccessToken extract(Response response); void generateError(String rawResponse); } | @Test public void shouldParseResponse() throws IOException { final String responseBody = "{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X\", " + "\"token_type\":\"example\"}"; final OAuth2AccessToken token; try (Response response = ok(responseBody)) { token = extractor.extract(response); } assertEquals("I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X", token.getAccessToken()); }
@Test public void shouldParseScopeFromResponse() throws IOException { final String responseBody = "{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T4X\", " + "\"token_type\":\"example\"," + "\"scope\":\"s1\"}"; final OAuth2AccessToken token; try (Response response = ok(responseBody)) { token = extractor.extract(response); } assertEquals("I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T4X", token.getAccessToken()); assertEquals("s1", token.getScope()); final String responseBody2 = "{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T5X\", " + "\"token_type\":\"example\"," + "\"scope\":\"s1 s2\"}"; final OAuth2AccessToken token2; try (Response response = ok(responseBody2)) { token2 = extractor.extract(response); } assertEquals("I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T5X", token2.getAccessToken()); assertEquals("s1 s2", token2.getScope()); final String responseBody3 = "{ \"access_token\":\"I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T6X\", " + "\"token_type\":\"example\"," + "\"scope\":\"s3 s4\", " + "\"refresh_token\":\"refresh_token1\"}"; final OAuth2AccessToken token3; try (Response response = ok(responseBody3)) { token3 = extractor.extract(response); } assertEquals("I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T6X", token3.getAccessToken()); assertEquals("s3 s4", token3.getScope()); assertEquals("refresh_token1", token3.getRefreshToken()); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfForNullParameters() throws IOException { try (Response response = ok(null)) { extractor.extract(response); } }
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfForEmptyStrings() throws IOException { final String responseBody = ""; try (Response response = ok(responseBody)) { extractor.extract(response); } }
@Test public void shouldThrowExceptionIfResponseIsError() throws IOException { final String responseBody = "{" + "\"error_description\":\"unknown, invalid, or expired refresh token\"," + "\"error\":\"invalid_grant\"" + "}"; try (Response response = error(responseBody)) { extractor.extract(response); fail(); } catch (OAuth2AccessTokenErrorResponse oaer) { assertEquals(OAuth2Error.INVALID_GRANT, oaer.getError()); assertEquals("unknown, invalid, or expired refresh token", oaer.getErrorDescription()); } }
@Test public void testEscapedJsonInResponse() throws IOException { final String responseBody = "{ \"access_token\":\"I0122HKLEM2\\/MV3ABKFTDT3T5X\"," + "\"token_type\":\"example\"}"; final OAuth2AccessToken token; try (Response response = ok(responseBody)) { token = extractor.extract(response); } assertEquals("I0122HKLEM2/MV3ABKFTDT3T5X", token.getAccessToken()); } |
OAuth20Service extends OAuthService { public OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password) throws IOException, InterruptedException, ExecutionException { final OAuthRequest request = createAccessTokenPasswordGrantRequest(username, password, null); return sendAccessTokenRequestSync(request); } OAuth20Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope,
String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig,
HttpClient httpClient); Future<OAuth2AccessToken> getAccessTokenAsync(String code); Future<OAuth2AccessToken> getAccessTokenAsync(AccessTokenRequestParams params); OAuth2AccessToken getAccessToken(String code); OAuth2AccessToken getAccessToken(AccessTokenRequestParams params); Future<OAuth2AccessToken> getAccessToken(AccessTokenRequestParams params,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessToken(String code,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken); Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken, String scope); OAuth2AccessToken refreshAccessToken(String refreshToken); OAuth2AccessToken refreshAccessToken(String refreshToken, String scope); Future<OAuth2AccessToken> refreshAccessToken(String refreshToken,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password); OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password, String scope); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(String scope); OAuth2AccessToken getAccessTokenClientCredentialsGrant(); OAuth2AccessToken getAccessTokenClientCredentialsGrant(String scope); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); @Override String getVersion(); void signRequest(String accessToken, OAuthRequest request); void signRequest(OAuth2AccessToken accessToken, OAuthRequest request); String getAuthorizationUrl(); String getAuthorizationUrl(String state); String getAuthorizationUrl(Map<String, String> additionalParams); String getAuthorizationUrl(PKCE pkce); AuthorizationUrlBuilder createAuthorizationUrlBuilder(); DefaultApi20 getApi(); Future<Void> revokeTokenAsync(String tokenToRevoke); Future<Void> revokeTokenAsync(String tokenToRevoke, TokenTypeHint tokenTypeHint); void revokeToken(String tokenToRevoke); void revokeToken(String tokenToRevoke, TokenTypeHint tokenTypeHint); Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback); Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback,
TokenTypeHint tokenTypeHint); OAuth2Authorization extractAuthorization(String redirectLocation); String getResponseType(); String getDefaultScope(); } | @Test public void shouldProduceCorrectRequestSync() throws IOException, InterruptedException, ExecutionException { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); final OAuth2AccessToken token = service.getAccessTokenPasswordGrant("user1", "password1"); assertNotNull(token); final JsonNode response = OBJECT_MAPPER.readTree(token.getRawResponse()); assertEquals(OAuth20ServiceUnit.TOKEN, response.get(OAuthConstants.ACCESS_TOKEN).asText()); assertEquals(OAuth20ServiceUnit.EXPIRES, response.get("expires_in").asInt()); final String authorize = base64Encoder.encodeToString( String.format("%s:%s", service.getApiKey(), service.getApiSecret()).getBytes(Charset.forName("UTF-8"))); assertEquals(OAuthConstants.BASIC + ' ' + authorize, response.get(OAuthConstants.HEADER).asText()); assertEquals("user1", response.get("query-username").asText()); assertEquals("password1", response.get("query-password").asText()); assertEquals("password", response.get("query-grant_type").asText()); } |
OAuth20Service extends OAuthService { public Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password) { return getAccessTokenPasswordGrantAsync(username, password, (OAuthAsyncRequestCallback<OAuth2AccessToken>) null); } OAuth20Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope,
String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig,
HttpClient httpClient); Future<OAuth2AccessToken> getAccessTokenAsync(String code); Future<OAuth2AccessToken> getAccessTokenAsync(AccessTokenRequestParams params); OAuth2AccessToken getAccessToken(String code); OAuth2AccessToken getAccessToken(AccessTokenRequestParams params); Future<OAuth2AccessToken> getAccessToken(AccessTokenRequestParams params,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessToken(String code,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken); Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken, String scope); OAuth2AccessToken refreshAccessToken(String refreshToken); OAuth2AccessToken refreshAccessToken(String refreshToken, String scope); Future<OAuth2AccessToken> refreshAccessToken(String refreshToken,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password); OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password, String scope); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(String scope); OAuth2AccessToken getAccessTokenClientCredentialsGrant(); OAuth2AccessToken getAccessTokenClientCredentialsGrant(String scope); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); @Override String getVersion(); void signRequest(String accessToken, OAuthRequest request); void signRequest(OAuth2AccessToken accessToken, OAuthRequest request); String getAuthorizationUrl(); String getAuthorizationUrl(String state); String getAuthorizationUrl(Map<String, String> additionalParams); String getAuthorizationUrl(PKCE pkce); AuthorizationUrlBuilder createAuthorizationUrlBuilder(); DefaultApi20 getApi(); Future<Void> revokeTokenAsync(String tokenToRevoke); Future<Void> revokeTokenAsync(String tokenToRevoke, TokenTypeHint tokenTypeHint); void revokeToken(String tokenToRevoke); void revokeToken(String tokenToRevoke, TokenTypeHint tokenTypeHint); Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback); Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback,
TokenTypeHint tokenTypeHint); OAuth2Authorization extractAuthorization(String redirectLocation); String getResponseType(); String getDefaultScope(); } | @Test public void shouldProduceCorrectRequestAsync() throws ExecutionException, InterruptedException, IOException { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); final OAuth2AccessToken token = service.getAccessTokenPasswordGrantAsync("user1", "password1").get(); assertNotNull(token); final JsonNode response = OBJECT_MAPPER.readTree(token.getRawResponse()); assertEquals(OAuth20ServiceUnit.TOKEN, response.get(OAuthConstants.ACCESS_TOKEN).asText()); assertEquals(OAuth20ServiceUnit.EXPIRES, response.get("expires_in").asInt()); final String authorize = base64Encoder.encodeToString( String.format("%s:%s", service.getApiKey(), service.getApiSecret()).getBytes(Charset.forName("UTF-8"))); assertEquals(OAuthConstants.BASIC + ' ' + authorize, response.get(OAuthConstants.HEADER).asText()); assertEquals("user1", response.get("query-username").asText()); assertEquals("password1", response.get("query-password").asText()); assertEquals("password", response.get("query-grant_type").asText()); } |
OAuth20Service extends OAuthService { public OAuth2Authorization extractAuthorization(String redirectLocation) { final OAuth2Authorization authorization = new OAuth2Authorization(); int end = redirectLocation.indexOf('#'); if (end == -1) { end = redirectLocation.length(); } for (String param : redirectLocation.substring(redirectLocation.indexOf('?') + 1, end).split("&")) { final String[] keyValue = param.split("="); if (keyValue.length == 2) { try { switch (keyValue[0]) { case "code": authorization.setCode(URLDecoder.decode(keyValue[1], "UTF-8")); break; case "state": authorization.setState(URLDecoder.decode(keyValue[1], "UTF-8")); break; default: } } catch (UnsupportedEncodingException ueE) { throw new IllegalStateException("jvm without UTF-8, really?", ueE); } } } return authorization; } OAuth20Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope,
String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig,
HttpClient httpClient); Future<OAuth2AccessToken> getAccessTokenAsync(String code); Future<OAuth2AccessToken> getAccessTokenAsync(AccessTokenRequestParams params); OAuth2AccessToken getAccessToken(String code); OAuth2AccessToken getAccessToken(AccessTokenRequestParams params); Future<OAuth2AccessToken> getAccessToken(AccessTokenRequestParams params,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessToken(String code,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken); Future<OAuth2AccessToken> refreshAccessTokenAsync(String refreshToken, String scope); OAuth2AccessToken refreshAccessToken(String refreshToken); OAuth2AccessToken refreshAccessToken(String refreshToken, String scope); Future<OAuth2AccessToken> refreshAccessToken(String refreshToken,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> refreshAccessToken(String refreshToken, String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password); OAuth2AccessToken getAccessTokenPasswordGrant(String username, String password, String scope); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenPasswordGrantAsync(String username, String password, String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(String scope); OAuth2AccessToken getAccessTokenClientCredentialsGrant(); OAuth2AccessToken getAccessTokenClientCredentialsGrant(String scope); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); Future<OAuth2AccessToken> getAccessTokenClientCredentialsGrant(String scope,
OAuthAsyncRequestCallback<OAuth2AccessToken> callback); @Override String getVersion(); void signRequest(String accessToken, OAuthRequest request); void signRequest(OAuth2AccessToken accessToken, OAuthRequest request); String getAuthorizationUrl(); String getAuthorizationUrl(String state); String getAuthorizationUrl(Map<String, String> additionalParams); String getAuthorizationUrl(PKCE pkce); AuthorizationUrlBuilder createAuthorizationUrlBuilder(); DefaultApi20 getApi(); Future<Void> revokeTokenAsync(String tokenToRevoke); Future<Void> revokeTokenAsync(String tokenToRevoke, TokenTypeHint tokenTypeHint); void revokeToken(String tokenToRevoke); void revokeToken(String tokenToRevoke, TokenTypeHint tokenTypeHint); Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback); Future<Void> revokeToken(String tokenToRevoke, OAuthAsyncRequestCallback<Void> callback,
TokenTypeHint tokenTypeHint); OAuth2Authorization extractAuthorization(String redirectLocation); String getResponseType(); String getDefaultScope(); } | @Test public void testOAuthExtractAuthorization() { final OAuth20Service service = new ServiceBuilder("your_api_key") .apiSecret("your_api_secret") .build(new OAuth20ApiUnit()); OAuth2Authorization authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals("xyz", authorization.getState()); authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https: assertEquals("SplxlOB", authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https: assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https: assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https: assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); authorization = service.extractAuthorization("https: assertEquals(null, authorization.getCode()); assertEquals(null, authorization.getState()); } |
OAuthAsyncCompletionHandler implements Callback { @Override public void onFailure(Call call, IOException exception) { try { okHttpFuture.setException(exception); if (callback != null) { callback.onThrowable(exception); } } finally { okHttpFuture.finish(); } } OAuthAsyncCompletionHandler(OAuthAsyncRequestCallback<T> callback, OAuthRequest.ResponseConverter<T> converter,
OkHttpFuture<T> okHttpFuture); @Override void onFailure(Call call, IOException exception); @Override void onResponse(Call call, okhttp3.Response okHttpResponse); } | @Test public void shouldReleaseLatchOnFailure() throws Exception { handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER, future); call.enqueue(handler); handler.onFailure(call, new IOException()); assertNull(callback.getResponse()); assertNotNull(callback.getThrowable()); assertTrue(callback.getThrowable() instanceof IOException); try { future.get(); fail(); } catch (ExecutionException expected) { } } |
HMACSha1SignatureService implements SignatureService { @Override public String getSignatureMethod() { return METHOD; } @Override String getSignature(String baseString, String apiSecret, String tokenSecret); @Override String getSignatureMethod(); } | @Test public void shouldReturnSignatureMethodString() { final String expected = "HMAC-SHA1"; assertEquals(expected, service.getSignatureMethod()); } |
CSRFToken implements Serializable { public String getParameterName() { return parameterName; } CSRFToken(String token); CSRFToken(String headerName, String parameterName, String token); String getHeaderName(); String getParameterName(); String getToken(); } | @Test public void testPOSTRequestsWithWrongToken() throws Exception { this.mockMvc.perform(post("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); }
@Test public void testPUTRequestsWithWrongToken() throws Exception { this.mockMvc.perform(put("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); }
@Test public void testDELETERequestsWithWrongToken() throws Exception { this.mockMvc.perform(delete("/test/csrf").param(TEST_TOKEN.getParameterName(), "WRONG_TOKEN")).andExpect( status().isBadRequest()); } |
FileSystemLogRepository implements ExecutionLogRepository { @Override public void update(ExecutionLog log) { store(log, readJson(logFileFor(log.getTaskName(), log.getId())).map(obj -> obj.getAsJsonPrimitive("previous")).map( JsonPrimitive::getAsString)); } FileSystemLogRepository(String basePath, int dispersionFactor); FileSystemLogRepository(int dispersionFactor); void setBasePath(String basePath); @Override void update(ExecutionLog log); @Override void newExecution(ExecutionLog log); @Override void appendTaskLog(ExecutionLog log, String text); @Override void storeFile(ExecutionLog log, String fileName, byte[] contents, boolean append); @Override Stream<ExecutionLog> latest(); @Override Stream<ExecutionLog> executionsFor(String taskName, Optional<String> start, int max); @Override Optional<String> getTaskLog(String taskName, String id); @Override Optional<byte[]> getFile(String taskName, String id, String fileName); @Override Optional<ExecutionLog> getLog(String taskName, String id); } | @Test public void testUpdate() { ExecutionLog original = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(original); assertEquals(original, repository.getLog(original.getTaskName(), original.getId()).get()); ExecutionLog log = original.withSuccess(); repository.update(log); assertEquals(log, repository.getLog(original.getTaskName(), original.getId()).get()); } |
FileSystemLogRepository implements ExecutionLogRepository { @Override public Stream<ExecutionLog> executionsFor(String taskName, Optional<String> start, int max) { String id; if (start.isPresent()) { id = start.get(); } else { JsonObject index = readIndexJson(); if (!index.has(taskName)) { return Stream.empty(); } id = index.get(taskName).getAsString(); } List<ExecutionLog> logs = new ArrayList<>(Math.min(max, 100)); while (id != null && max > 0) { Optional<JsonObject> optional = readJson(logFileFor(taskName, id)); if (optional.isPresent()) { JsonObject json = optional.get(); id = json.has("previous") ? json.get("previous").getAsString() : null; logs.add(new ExecutionLog(json)); max--; } else { break; } } return logs.stream(); } FileSystemLogRepository(String basePath, int dispersionFactor); FileSystemLogRepository(int dispersionFactor); void setBasePath(String basePath); @Override void update(ExecutionLog log); @Override void newExecution(ExecutionLog log); @Override void appendTaskLog(ExecutionLog log, String text); @Override void storeFile(ExecutionLog log, String fileName, byte[] contents, boolean append); @Override Stream<ExecutionLog> latest(); @Override Stream<ExecutionLog> executionsFor(String taskName, Optional<String> start, int max); @Override Optional<String> getTaskLog(String taskName, String id); @Override Optional<byte[]> getFile(String taskName, String id, String fileName); @Override Optional<ExecutionLog> getLog(String taskName, String id); } | @Test public void testExecutionsFor() { ExecutionLog original = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(original); ExecutionLog newLog = ExecutionLog.newExecutionFor(TASK_NAME); repository.newExecution(newLog); assertTrue(repository.executionsFor(original.getTaskName(), Optional.empty(), Integer.MAX_VALUE).anyMatch( l -> l.equals(original))); assertTrue(repository.executionsFor(newLog.getTaskName(), Optional.empty(), Integer.MAX_VALUE).anyMatch( l -> l.equals(newLog))); } |
ExecutionLog { public static ExecutionLog newExecutionFor(String taskName) { return new ExecutionLog(UUID.randomUUID().toString().replace("-", ""), DateTime.now(), Optional.empty(), TaskState.RUNNING, Objects.requireNonNull(taskName), Optional.empty(), Collections.emptySet(), computeHostName(), Optional.empty(), Optional.empty()); } protected ExecutionLog(JsonObject json); private ExecutionLog(String id, DateTime start, Optional<DateTime> end, TaskState state, String taskName,
Optional<String> stackTrace, Set<String> files, String hostname, Optional<String> code, Optional<String> user); static ExecutionLog newExecutionFor(String taskName); static ExecutionLog newCustomExecution(String taskName, String code, String user); String getId(); DateTime getStart(); Optional<DateTime> getEnd(); TaskState getState(); String getTaskName(); Optional<String> getStackTrace(); Set<String> getFiles(); String getHostname(); Optional<String> getCode(); Optional<String> getUser(); ExecutionLog withSuccess(); ExecutionLog withError(Throwable t); ExecutionLog withFile(String filename); JsonObject json(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test(expected = NullPointerException.class) public void testNullTaskName() { ExecutionLog.newExecutionFor(null); } |
ExecutionLog { public static ExecutionLog newCustomExecution(String taskName, String code, String user) { return new ExecutionLog(UUID.randomUUID().toString().replace("-", ""), DateTime.now(), Optional.empty(), TaskState.RUNNING, Objects.requireNonNull(taskName), Optional.empty(), Collections.emptySet(), computeHostName(), Optional.of(code), Optional.of(user)); } protected ExecutionLog(JsonObject json); private ExecutionLog(String id, DateTime start, Optional<DateTime> end, TaskState state, String taskName,
Optional<String> stackTrace, Set<String> files, String hostname, Optional<String> code, Optional<String> user); static ExecutionLog newExecutionFor(String taskName); static ExecutionLog newCustomExecution(String taskName, String code, String user); String getId(); DateTime getStart(); Optional<DateTime> getEnd(); TaskState getState(); String getTaskName(); Optional<String> getStackTrace(); Set<String> getFiles(); String getHostname(); Optional<String> getCode(); Optional<String> getUser(); ExecutionLog withSuccess(); ExecutionLog withError(Throwable t); ExecutionLog withFile(String filename); JsonObject json(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test(expected = NullPointerException.class) public void testNullTaskNameOnCustomTask() { ExecutionLog.newCustomExecution(null, "code", "myself"); }
@Test(expected = NullPointerException.class) public void testNullCode() { ExecutionLog.newCustomExecution(TASK_NAME, null, "myself"); }
@Test(expected = NullPointerException.class) public void testNullTaskNamesDontWork() { ExecutionLog.newCustomExecution(TASK_NAME, "code", null); } |
ExecutionLog { @Override public boolean equals(Object obj) { if (obj instanceof ExecutionLog) { ExecutionLog other = (ExecutionLog) obj; return Objects.equals(id, other.id) && Objects.equals(start, other.start) && Objects.equals(end, other.end) && Objects.equals(state, other.state) && Objects.equals(taskName, other.taskName) && Objects.equals(stackTrace, other.stackTrace) && Objects.equals(hostname, other.hostname) && Objects.equals(files, other.files) && Objects.equals(code, other.code) && Objects.equals(user, other.user); } return false; } protected ExecutionLog(JsonObject json); private ExecutionLog(String id, DateTime start, Optional<DateTime> end, TaskState state, String taskName,
Optional<String> stackTrace, Set<String> files, String hostname, Optional<String> code, Optional<String> user); static ExecutionLog newExecutionFor(String taskName); static ExecutionLog newCustomExecution(String taskName, String code, String user); String getId(); DateTime getStart(); Optional<DateTime> getEnd(); TaskState getState(); String getTaskName(); Optional<String> getStackTrace(); Set<String> getFiles(); String getHostname(); Optional<String> getCode(); Optional<String> getUser(); ExecutionLog withSuccess(); ExecutionLog withError(Throwable t); ExecutionLog withFile(String filename); JsonObject json(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void testEquals() { ExecutionLog log = ExecutionLog.newExecutionFor(TASK_NAME); ExecutionLog custom = ExecutionLog.newCustomExecution(TASK_NAME, "mycode", "myself"); assertEquals(log, log); assertNotEquals(log, log.withSuccess()); assertNotEquals(log, log.withFile("xpto")); assertNotEquals(log, log.withError(new Throwable())); assertNotEquals(log, ExecutionLog.newExecutionFor(TASK_NAME)); assertNotEquals(log, ExecutionLog.newExecutionFor("SOME_OTHER_TASK_NAME")); assertNotEquals(log, custom); assertNotEquals(custom, ExecutionLog.newCustomExecution(TASK_NAME, "othercode", "myself")); assertNotEquals(custom, ExecutionLog.newCustomExecution(TASK_NAME, "mycode", "another")); } |
GuitarString { public void tic() { double newAveragedDouble = DECAY * (buffer.dequeue() + buffer.peek()) / 2; buffer.enqueue(newAveragedDouble); } GuitarString(double frequency); void pluck(); void tic(); double sample(); } | @Test public void testTic() { GuitarString s = new GuitarString(11025); s.pluck(); double s1 = s.sample(); s.tic(); double s2 = s.sample(); s.tic(); double s3 = s.sample(); s.tic(); double s4 = s.sample(); s.tic(); double s5 = s.sample(); double expected = 0.996 * 0.5 * (s1 + s2); assertEquals(expected, s5, 0.001); } |
Plip extends Creature { public Action chooseAction(Map<Direction, Occupant> neighbors) { List<Direction> emptySpaces = getNeighborsOfType(neighbors, "empty"); List<Direction> cloruses = getNeighborsOfType(neighbors, "clorus"); if (emptySpaces.isEmpty()) { return new Action(Action.ActionType.STAY); } if (energy > 1) { Direction moveDir = HugLifeUtils.randomEntry(emptySpaces); return new Action(Action.ActionType.REPLICATE, moveDir); } if (!cloruses.isEmpty()) { if (HugLifeUtils.random() < 0.5) { Direction moveDir = HugLifeUtils.randomEntry(emptySpaces); return new Action(Action.ActionType.MOVE, moveDir); } } return new Action(Action.ActionType.STAY); } Plip(double e); Plip(); Color color(); void attack(Creature c); void move(); void stay(); Plip replicate(); Action chooseAction(Map<Direction, Occupant> neighbors); } | @Test public void testChoose() { Plip p = new Plip(1.2); HashMap<Direction, Occupant> surrounded = new HashMap<Direction, Occupant>(); surrounded.put(Direction.TOP, new Impassible()); surrounded.put(Direction.BOTTOM, new Impassible()); surrounded.put(Direction.LEFT, new Impassible()); surrounded.put(Direction.RIGHT, new Impassible()); Action actual = p.chooseAction(surrounded); Action expected = new Action(Action.ActionType.STAY); assertEquals(expected, actual); } |
Board implements WorldState { public int tileAt(int i, int j) { if (i < 0 || i >= N || j < 0 || j >= N) { throw new IndexOutOfBoundsException("Invalid row and/or column"); } return tiles[i][j]; } Board(int[][] tiles); int tileAt(int i, int j); int size(); int hamming(); int manhattan(); int hashCode(); boolean equals(Object y); @Override int estimatedDistanceToGoal(); @Override Iterable<WorldState> neighbors(); @Override boolean isGoal(); String toString(); } | @Test public void verifyImmutability() { int r = 2; int c = 2; int[][] x = new int[r][c]; int cnt = 0; for (int i = 0; i < r; i += 1) { for (int j = 0; j < c; j += 1) { x[i][j] = cnt; cnt += 1; } } Board b = new Board(x); assertEquals("Your Board class is not being initialized with the right values.", 0, b.tileAt(0, 0)); assertEquals("Your Board class is not being initialized with the right values.", 1, b.tileAt(0, 1)); assertEquals("Your Board class is not being initialized with the right values.", 2, b.tileAt(1, 0)); assertEquals("Your Board class is not being initialized with the right values.", 3, b.tileAt(1, 1)); x[1][1] = 1000; assertEquals("Your Board class is mutable and you should be making a copy of the values in the passed tiles array. Please see the FAQ!", 3, b.tileAt(1, 1)); } |
IntList { public static IntList list(Integer... args) { IntList result, p; if (args.length > 0) { result = new IntList(args[0], null); } else { return null; } int k; for (k = 1, p = result; k < args.length; k += 1, p = p.rest) { p.rest = new IntList(args[k], null); } return result; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; } | @Test public void testList() { IntList one = new IntList(1, null); IntList twoOne = new IntList(2, one); IntList threeTwoOne = new IntList(3, twoOne); IntList x = IntList.list(3, 2, 1); assertEquals(threeTwoOne, x); } |
IntList { public static void dSquareList(IntList L) { while (L != null) { L.first = L.first * L.first; L = L.rest; } } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; } | @Test public void testdSquareList() { IntList L = IntList.list(1, 2, 3); IntList.dSquareList(L); assertEquals(IntList.list(1, 4, 9), L); } |
IntList { public static IntList squareListRecursive(IntList L) { if (L == null) { return null; } return new IntList(L.first * L.first, squareListRecursive(L.rest)); } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; } | @Test public void testSquareListRecursive() { IntList L = IntList.list(1, 2, 3); IntList res = IntList.squareListRecursive(L); assertEquals(IntList.list(1, 2, 3), L); assertEquals(IntList.list(1, 4, 9), res); } |
IntList { public static IntList dcatenate(IntList A, IntList B) { return null; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; } | @Test public void testDcatenate() { IntList A = IntList.list(1, 2, 3); IntList B = IntList.list(4, 5, 6); IntList exp = IntList.list(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.dcatenate(A, B)); assertEquals(IntList.list(1, 2, 3, 4, 5, 6), A); } |
IntList { public static IntList catenate(IntList A, IntList B) { return null; } IntList(int first0, IntList rest0); IntList(); static void dSquareList(IntList L); static IntList squareListIterative(IntList L); static IntList squareListRecursive(IntList L); static IntList dcatenate(IntList A, IntList B); static IntList catenate(IntList A, IntList B); @Override int hashCode(); static IntList list(Integer... args); boolean equals(Object x); @Override /** Outputs the IntList as a String. You are not expected to read * or understand this method. */ String toString(); public int first; public IntList rest; } | @Test public void testCatenate() { IntList A = IntList.list(1, 2, 3); IntList B = IntList.list(4, 5, 6); IntList exp = IntList.list(1, 2, 3, 4, 5, 6); assertEquals(exp, IntList.catenate(A, B)); assertEquals(IntList.list(1, 2, 3), A); } |
Boggle { public static String answerString(List<String> answers, int numberOfAnswers) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < answers.size() && i < numberOfAnswers; i++) { sb.append(answers.get(i)).append('\n'); } sb.setLength(sb.length() - 1); return sb.toString(); } static void main(String[] args); static String answerString(List<String> answers, int numberOfAnswers); } | @Test public void solveBoard() { List<String> boardLines = null; List<String> dictionaryWords = null; try { boardLines = Files.readAllLines(Paths.get("testBoggle")); dictionaryWords = Files.readAllLines(Paths.get("words")); } catch (IOException e) { e.printStackTrace(); } Board board = new Board(boardLines, dictionaryWords); String expected = "thumbtacks\n" + "thumbtack\n" + "setbacks\n" + "setback\n" + "ascent\n" + "humane\n" + "smacks"; assertEquals(expected, Boggle.answerString(board.getAnswers(), 7)); try { boardLines = Files.readAllLines(Paths.get("testBoggle2")); dictionaryWords = Files.readAllLines(Paths.get("testDict")); } catch (IOException e) { e.printStackTrace(); } board = new Board(boardLines, dictionaryWords); expected = "aaaaa\n" + "aaaa"; assertEquals(expected, Boggle.answerString(board.getAnswers(), 20)); } |
Arithmetic { public static int product(int a, int b) { return a * b; } static int product(int a, int b); static int sum(int a, int b); } | @Test public void testProduct() { assertEquals(30, Arithmetic.product(5, 6)); assertEquals(-30, Arithmetic.product(5, -6)); assertEquals(0, Arithmetic.product(0, -6)); } |
Arithmetic { public static int sum(int a, int b) { return a * b; } static int product(int a, int b); static int sum(int a, int b); } | @Test public void testSum() { assertEquals(11, Arithmetic.sum(5, 6)); assertEquals(-1, Arithmetic.sum(5, -6)); assertEquals(-6, Arithmetic.sum(0, -6)); assertEquals(0, Arithmetic.sum(6, -6)); } |
Trie { public List<String> getWordsContainingPrefix(String prefix) { LinkedList<String> words = new LinkedList<>(); Node pointer = root; for (int i = 0; i < prefix.length(); i++) { char currentChar = prefix.charAt(i); if (!pointer.children.containsKey(currentChar)) { return words; } pointer = pointer.children.get(currentChar); } Node prefixEndNode = pointer; List<Node> endNodes = getAllEndNodesContainingPrefix(prefixEndNode); for (Node node : endNodes) { StringBuilder sb = new StringBuilder(); pointer = node; while (pointer != prefixEndNode) { sb.append(pointer.character); pointer = pointer.parent; } words.add(prefix + sb.reverse().toString()); } return words; } void add(String word); boolean containsWord(String word); List<String> getWordsContainingPrefix(String prefix); } | @Test public void getWordsContainingPrefix() { Trie trie = new Trie(); trie.add("app"); trie.add("appearance"); trie.add("apple"); trie.add("appliance"); trie.add("application"); trie.add("montclair"); trie.add("mountain"); List<String> wordsContainingPrefix = trie.getWordsContainingPrefix("foster"); assertEquals(0, wordsContainingPrefix.size()); wordsContainingPrefix = trie.getWordsContainingPrefix("mont"); List<String> expected = Arrays.asList("montclair"); assertEquals(expected, wordsContainingPrefix); wordsContainingPrefix = trie.getWordsContainingPrefix("app"); expected = Arrays.asList("app", "application", "appliance", "apple", "appearance"); assertEquals(expected, wordsContainingPrefix); } |
BinaryTrie implements Serializable { public Match longestPrefixMatch(BitSequence querySequence) { StringBuilder currentBitSeq = new StringBuilder(); Node pointer = root; for (int i = 0; i < querySequence.length(); i++) { if (querySequence.bitAt(i) == 0 && pointer.leftChild != null) { currentBitSeq.append('0'); pointer = pointer.leftChild; } else if (querySequence.bitAt(i) == 1 && pointer.rightChild != null) { currentBitSeq.append('1'); pointer = pointer.rightChild; } else { break; } } return new Match(new BitSequence(currentBitSeq.toString()), pointer.character); } BinaryTrie(Map<Character, Integer> frequencyTable); Match longestPrefixMatch(BitSequence querySequence); Map<Character, BitSequence> buildLookupTable(); } | @Test public void bestPrefixMatchWithExactMatches() { System.out.println("Testing that bestPrefixMatch works with exact matches."); Map<Character, Integer> frequencyTable = new HashMap<Character, Integer>(); frequencyTable.put('a', 1); frequencyTable.put('b', 2); frequencyTable.put('c', 4); frequencyTable.put('d', 5); frequencyTable.put('e', 6); BinaryTrie trie = new BinaryTrie(frequencyTable); BitSequence shouldBeA = new BitSequence("000"); Match m = trie.longestPrefixMatch(shouldBeA); assertEquals((char) 'a', (char) m.getSymbol()); assertEquals(shouldBeA, m.getSequence()); BitSequence shouldBeE = new BitSequence("11"); m = trie.longestPrefixMatch(shouldBeE); assertEquals((char) 'e', (char) m.getSymbol()); assertEquals(shouldBeE, m.getSequence()); }
@Test public void bestPrefixMatchWithLongerBitSequences() { System.out.println("Testing that bestPrefixMatch works with long string matches."); Map<Character, Integer> frequencyTable = new HashMap<Character, Integer>(); frequencyTable.put('a', 1); frequencyTable.put('b', 2); frequencyTable.put('c', 4); frequencyTable.put('d', 5); frequencyTable.put('e', 6); BinaryTrie trie = new BinaryTrie(frequencyTable); BitSequence shouldBeA = new BitSequence("0001010001"); Match m = trie.longestPrefixMatch(shouldBeA); assertEquals((char) 'a', (char) m.getSymbol()); BitSequence justA = new BitSequence("000"); assertEquals(justA, m.getSequence()); BitSequence shouldBeE = new BitSequence("11000110001"); m = trie.longestPrefixMatch(shouldBeE); assertEquals((char) 'e', (char) m.getSymbol()); BitSequence justE = new BitSequence("11"); assertEquals(justE, m.getSequence()); BitSequence shouldBeAE = new BitSequence("00011"); m = trie.longestPrefixMatch(shouldBeA); assertEquals((char) 'a', (char) m.getSymbol()); assertEquals(justA, m.getSequence()); BitSequence remainingBits = shouldBeAE.allButFirstNBits(m.getSequence().length()); m = trie.longestPrefixMatch(remainingBits); assertEquals((char) 'e', (char) m.getSymbol()); assertEquals(justE, m.getSequence()); } |
BinaryTrie implements Serializable { public Map<Character, BitSequence> buildLookupTable() { Map<Character, BitSequence> lookupTable = new HashMap<>(); Map<Node, String> nodeBitPrefixTable = new HashMap<>(); nodeBitPrefixTable.put(root, ""); Stack<Node> nodeStack = new Stack<>(); nodeStack.push(root); while (!nodeStack.isEmpty()) { Node pointer = nodeStack.pop(); String currentBitSeq = nodeBitPrefixTable.get(pointer); if (pointer.rightChild != null) { nodeStack.push(pointer.rightChild); nodeBitPrefixTable.put(pointer.rightChild, currentBitSeq + '1'); } if (pointer.leftChild != null) { nodeStack.push(pointer.leftChild); nodeBitPrefixTable.put(pointer.leftChild, currentBitSeq + '0'); nodeBitPrefixTable.remove(pointer); } } for (char character : charNodeMap.keySet()) { Node charNode = charNodeMap.get(character); String bitSeqString = nodeBitPrefixTable.get(charNode); lookupTable.put(character, new BitSequence(bitSeqString)); } return lookupTable; } BinaryTrie(Map<Character, Integer> frequencyTable); Match longestPrefixMatch(BitSequence querySequence); Map<Character, BitSequence> buildLookupTable(); } | @Test public void testYourLookupTable() { System.out.println("Testing that your code outputs the right lookup table."); Map<Character, Integer> frequencyTable = new HashMap<Character, Integer>(); frequencyTable.put('a', 1); frequencyTable.put('b', 2); frequencyTable.put('c', 4); frequencyTable.put('d', 5); frequencyTable.put('e', 6); BinaryTrie trie = new BinaryTrie(frequencyTable); Map<Character, BitSequence> yourTable = trie.buildLookupTable(); HashMap<Character, BitSequence> expected = new HashMap<Character, BitSequence>(); expected.put('a', new BitSequence("000")); expected.put('b', new BitSequence("001")); expected.put('c', new BitSequence("01")); expected.put('d', new BitSequence("10")); expected.put('e', new BitSequence("11")); assertEquals(expected, yourTable); } |
Dog { public String noise() { if (size < 10) { return "yip"; } return "bark"; } Dog(int s); String noise(); } | @Test public void testSmall() { Dog d = new Dog(3); assertEquals("yip", d.noise()); }
@Test public void testLarge() { Dog d = new Dog(20); assertEquals("bark", d.noise()); } |
SimpleOomage implements Oomage { @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } if (this == o || this.hashCode() == o.hashCode()) { return true; } return false; } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o); @Override int hashCode(); @Override void draw(double x, double y, double scalingFactor); static SimpleOomage randomSimpleOomage(); static void main(String[] args); String toString(); } | @Test public void testEquals() { SimpleOomage ooA = new SimpleOomage(5, 10, 20); SimpleOomage ooA2 = new SimpleOomage(5, 10, 20); SimpleOomage ooB = new SimpleOomage(50, 50, 50); assertEquals(ooA, ooA2); assertNotEquals(ooA, ooB); assertNotEquals(ooA2, ooB); assertNotEquals(ooA, "ketchup"); } |
SimpleOomage implements Oomage { public static SimpleOomage randomSimpleOomage() { int red = StdRandom.uniform(0, 51) * 5; int green = StdRandom.uniform(0, 51) * 5; int blue = StdRandom.uniform(0, 51) * 5; return new SimpleOomage(red, green, blue); } SimpleOomage(int r, int g, int b); @Override boolean equals(Object o); @Override int hashCode(); @Override void draw(double x, double y, double scalingFactor); static SimpleOomage randomSimpleOomage(); static void main(String[] args); String toString(); } | @Test public void testRandomOomagesHashCodeSpread() { List<Oomage> oomages = new ArrayList<>(); int N = 10000; for (int i = 0; i < N; i += 1) { oomages.add(SimpleOomage.randomSimpleOomage()); } assertTrue(OomageTestUtility.haveNiceHashCodeSpread(oomages, 10)); } |
Clorus extends Creature { @Override public Clorus replicate() { energy /= 2; return new Clorus(energy); } Clorus(double energy); @Override void move(); @Override void attack(Creature c); @Override Clorus replicate(); @Override void stay(); @Override Action chooseAction(Map<Direction, Occupant> neighbors); @Override Color color(); } | @Test public void testReplicate() { Clorus c = new Clorus(2); Clorus offspring = c.replicate(); assertEquals(1, c.energy(), 0.01); assertEquals(1, offspring.energy(), 0.01); assertNotSame(c, offspring); } |
Clorus extends Creature { @Override public Action chooseAction(Map<Direction, Occupant> neighbors) { List<Direction> emptySpaces = getNeighborsOfType(neighbors, "empty"); List<Direction> plips = getNeighborsOfType(neighbors, "plip"); if (emptySpaces.isEmpty()) { return new Action(Action.ActionType.STAY); } if (!plips.isEmpty()) { Direction moveDir = HugLifeUtils.randomEntry(plips); return new Action(Action.ActionType.ATTACK, moveDir); } if (energy >= 1) { Direction moveDir = HugLifeUtils.randomEntry(emptySpaces); return new Action(Action.ActionType.REPLICATE, moveDir); } Direction moveDir = HugLifeUtils.randomEntry(emptySpaces); return new Action(Action.ActionType.MOVE, moveDir); } Clorus(double energy); @Override void move(); @Override void attack(Creature c); @Override Clorus replicate(); @Override void stay(); @Override Action chooseAction(Map<Direction, Occupant> neighbors); @Override Color color(); } | @Test public void testChoose() { Clorus c = new Clorus(5); HashMap<Direction, Occupant> noEmptySpaces = new HashMap<Direction, Occupant>(); noEmptySpaces.put(Direction.TOP, new Plip()); noEmptySpaces.put(Direction.BOTTOM, new Impassible()); noEmptySpaces.put(Direction.LEFT, new Plip()); noEmptySpaces.put(Direction.RIGHT, new Plip()); Action actual = c.chooseAction(noEmptySpaces); Action expected = new Action(Action.ActionType.STAY); assertEquals(expected, actual); HashMap<Direction, Occupant> plipsInSight = new HashMap<Direction, Occupant>(); plipsInSight.put(Direction.TOP, new Plip()); plipsInSight.put(Direction.BOTTOM, new Empty()); plipsInSight.put(Direction.LEFT, new Plip()); plipsInSight.put(Direction.RIGHT, new Plip()); assertEquals(Action.ActionType.ATTACK, c.chooseAction(plipsInSight).type); HashMap<Direction, Occupant> oneClorus = new HashMap<Direction, Occupant>(); oneClorus.put(Direction.TOP, new Clorus(1)); oneClorus.put(Direction.BOTTOM, new Empty()); oneClorus.put(Direction.LEFT, new Empty()); oneClorus.put(Direction.RIGHT, new Empty()); assertEquals(Action.ActionType.REPLICATE, c.chooseAction(oneClorus).type); c = new Clorus(0.5); assertEquals(Action.ActionType.MOVE, c.chooseAction(oneClorus).type); } |
Plip extends Creature { public Plip replicate() { energy /= 2; return new Plip(energy); } Plip(double e); Plip(); Color color(); void attack(Creature c); void move(); void stay(); Plip replicate(); Action chooseAction(Map<Direction, Occupant> neighbors); } | @Test public void testReplicate() { Plip p = new Plip(2); Plip offspring = p.replicate(); assertEquals(1, p.energy(), 0.01); assertEquals(1, offspring.energy(), 0.01); assertNotSame(p, offspring); } |
StringWritableCsv { public static StringBuffer writeTo(StringBuffer sb, StringWritable... values) throws IllegalArgumentException { checkNotNull(sb, "sb"); if(null == values || values.length == 0) { return sb; } writeStringWritableToStringBuffer(values[0], sb); int i = 1; while (i < values.length) { sb.append(','); writeStringWritableToStringBuffer(values[i], sb); i++; } return sb; } static StringBuffer writeTo(StringBuffer sb, StringWritable... values); static String[] parseFrom(String value, int n, int offset); static String[] parseFrom(String value, int n); static String[] parseFrom(String value); } | @Test public void writeToNullOrEmpty() { assertTrue(StringWritableCsv.writeTo(new StringBuffer()).length() == 0); assertTrue(StringWritableCsv.writeTo(new StringBuffer(), new CharAttributeValue[]{}).length() == 0); }
@Test public void writeToOneArg() { CharAttributeValue[] pairs = new CharAttributeValue[] { new ScramAttributeValue(ScramAttributes.CHANNEL_BINDING, "channel"), new ScramAttributeValue(ScramAttributes.ITERATION, "" + 4096), new Gs2AttributeValue(Gs2Attributes.AUTHZID, "authzid"), new Gs2AttributeValue(Gs2Attributes.CLIENT_NOT, null) }; for(int i = 0; i < pairs.length; i++) { assertEquals(ONE_ARG_VALUES[i], StringWritableCsv.writeTo(new StringBuffer(), pairs[i]).toString()); } }
@Test public void writeToSeveralArgs() { assertEquals( SEVERAL_VALUES_STRING, StringWritableCsv.writeTo( new StringBuffer(), new Gs2AttributeValue(Gs2Attributes.CLIENT_NOT, null), null, new ScramAttributeValue(ScramAttributes.USERNAME, "user"), new ScramAttributeValue(ScramAttributes.NONCE, "fyko+d2lbbFgONRv9qkxdawL") ).toString() ); } |
UsAsciiUtils { public static String toPrintable(String value) throws IllegalArgumentException { checkNotNull(value, "value"); char[] printable = new char[value.length()]; int i = 0; for(char chr : value.toCharArray()) { int c = (int) chr; if (c < 0 || c >= 127) { throw new IllegalArgumentException("value contains character '" + chr + "' which is non US-ASCII"); } else if (c > 32) { printable[i++] = chr; } } return i == value.length() ? value : new String(printable, 0, i); } static String toPrintable(String value); } | @Test public void toPrintableNonASCII() { String[] nonASCIIStrings = new String[] { "abcdé", "ñ", "€", "Наташа", (char) 127 + "" }; int n = 0; for(String s : nonASCIIStrings) { try { UsAsciiUtils.toPrintable(s); } catch(IllegalArgumentException ex) { n++; } } assertTrue( "String(s) with non-ASCII characters not throwing IllegalArgumentException", n == nonASCIIStrings.length ); }
@Test public void toPrintableNonPrintable() { String[] original = new String[] { " u ", "a" + (char) 12, (char) 0 + "ttt" + (char) 31 }; String[] expected = new String[] { "u", "a", "ttt" }; for(int i = 0; i < original.length; i++) { assertEquals("", expected[i], UsAsciiUtils.toPrintable(original[i])); } }
@Test public void toPrintableAllPrintable() { List<String> values = new ArrayList<String>(); values.addAll(Arrays.asList( new String[] { (char) 33 + "", "user", "!", "-,.=?", (char) 126 + "" }) ); for(int c = 33; c < 127; c++) { values.add("---" + (char) c + "---"); } for(String s : values) { assertEquals( "All printable String '" + s + "' not returning the same value", s, UsAsciiUtils.toPrintable(s) ); } }
@Test public void toPrintableNull() { try { UsAsciiUtils.toPrintable(null); } catch(IllegalArgumentException ex) { return; } fail("Calling with null value must throw IllegalArgumentException"); } |
ServerFirstMessage implements StringWritable { @Override public String toString() { return writeTo(new StringBuffer()).toString(); } ServerFirstMessage(
String clientNonce, String serverNonce, String salt, int iteration
); String getClientNonce(); String getServerNonce(); String getNonce(); String getSalt(); int getIteration(); @Override StringBuffer writeTo(StringBuffer sb); static ServerFirstMessage parseFrom(String serverFirstMessage, String clientNonce); @Override String toString(); static final int ITERATION_MIN_VALUE; } | @Test public void validConstructor() { ServerFirstMessage serverFirstMessage = new ServerFirstMessage( CLIENT_NONCE, "3rfcNHYJY1ZVvWVs7j", "QSXCR+Q6sek8bf92", 4096 ); assertEquals(SERVER_FIRST_MESSAGE, serverFirstMessage.toString()); } |
ClientFirstMessage implements StringWritable { public static ClientFirstMessage parseFrom(String clientFirstMessage) throws ScramParseException, IllegalArgumentException { checkNotEmpty(clientFirstMessage, "clientFirstMessage"); Gs2Header gs2Header = Gs2Header.parseFrom(clientFirstMessage); String[] userNonceString; try { userNonceString = StringWritableCsv.parseFrom(clientFirstMessage, 2, 2); } catch (IllegalArgumentException e) { throw new ScramParseException("Illegal series of attributes in client-first-message", e); } ScramAttributeValue user = ScramAttributeValue.parse(userNonceString[0]); if(ScramAttributes.USERNAME.getChar() != user.getChar()) { throw new ScramParseException("user must be the 3rd element of the client-first-message"); } ScramAttributeValue nonce = ScramAttributeValue.parse(userNonceString[1]); if(ScramAttributes.NONCE.getChar() != nonce.getChar()) { throw new ScramParseException("nonce must be the 4th element of the client-first-message"); } return new ClientFirstMessage(gs2Header, user.getValue(), nonce.getValue()); } ClientFirstMessage(Gs2Header gs2Header, String user, String nonce); ClientFirstMessage(Gs2CbindFlag gs2CbindFlag, String authzid, String cbindName, String user, String nonce); ClientFirstMessage(String user, String nonce); Gs2CbindFlag getChannelBindingFlag(); boolean isChannelBinding(); Optional<String> getChannelBindingName(); Optional<String> getAuthzid(); Gs2Header getGs2Header(); String getUser(); String getNonce(); StringBuffer writeToWithoutGs2Header(StringBuffer sb); @Override StringBuffer writeTo(StringBuffer sb); static ClientFirstMessage parseFrom(String clientFirstMessage); @Override String toString(); } | @Test public void parseFromInvalidValues() { String[] invalidValues = new String[] { "n,,r=user,r=" + CLIENT_NONCE, "n,,z=user,r=" + CLIENT_NONCE, "n,,n=user", "n,", "n,,", "n,,n=user,r", "n,,n=user,r=" }; int n = 0; for(String s : invalidValues) { try { assertNotNull(ClientFirstMessage.parseFrom(s)); } catch (ScramParseException e) { n++; } } assertEquals(invalidValues.length, n); } |
ScramStringFormatting { public static String toSaslName(String value) { if(null == value || value.isEmpty()) { return value; } int nComma = 0, nEqual = 0; char[] originalChars = value.toCharArray(); for(char c : originalChars) { if(',' == c) { nComma++; } else if('=' == c) { nEqual++; } } if(nComma == 0 && nEqual == 0) { return value; } char[] saslChars = new char[originalChars.length + nComma * 2 + nEqual * 2]; int i = 0; for(char c : originalChars) { if(',' == c) { saslChars[i++] = '='; saslChars[i++] = '2'; saslChars[i++] = 'C'; } else if('=' == c) { saslChars[i++] = '='; saslChars[i++] = '3'; saslChars[i++] = 'D'; } else { saslChars[i++] = c; } } return new String(saslChars); } static String toSaslName(String value); static String fromSaslName(String value); static String base64Encode(byte[] value); static String base64Encode(String value); static byte[] base64Decode(String value); } | @Test public void toSaslNameNoCharactersToBeEscaped() { for(String s : VALUES_NO_CHARS_TO_BE_ESCAPED) { assertEquals(s, ScramStringFormatting.toSaslName(s)); } }
@Test public void toSaslNameWithCharactersToBeEscaped() { for(int i = 0; i < VALUES_TO_BE_ESCAPED.length; i++) { assertEquals(ESCAPED_VALUES[i], ScramStringFormatting.toSaslName(VALUES_TO_BE_ESCAPED[i])); } } |
ScramStringFormatting { public static String fromSaslName(String value) throws IllegalArgumentException { if(null == value || value.isEmpty()) { return value; } int nEqual = 0; char[] orig = value.toCharArray(); for(int i = 0; i < orig.length; i++) { if(orig[i] == ',') { throw new IllegalArgumentException("Invalid ',' character present in saslName"); } if(orig[i] == '=') { nEqual++; if(i + 2 > orig.length - 1) { throw new IllegalArgumentException("Invalid '=' character present in saslName"); } if(! (orig[i+1] == '2' && orig[i+2] == 'C' || orig[i+1] == '3' && orig[i+2] == 'D')) { throw new IllegalArgumentException( "Invalid char '=" + orig[i+1] + orig[i+2] + "' found in saslName" ); } } } if(nEqual == 0) { return value; } char[] replaced = new char[orig.length - nEqual * 2]; for(int r = 0, o = 0; r < replaced.length; r++) { if('=' == orig[o]) { if(orig[o+1] == '2' && orig[o+2] == 'C') { replaced[r] = ','; } else if(orig[o+1] == '3' && orig[o+2] == 'D') { replaced[r] = '='; } o += 3; } else { replaced[r] = orig[o]; o += 1; } } return new String(replaced); } static String toSaslName(String value); static String fromSaslName(String value); static String base64Encode(byte[] value); static String base64Encode(String value); static byte[] base64Decode(String value); } | @Test public void fromSaslNameNoCharactersToBeEscaped() { for(String s : VALUES_NO_CHARS_TO_BE_ESCAPED) { assertEquals(s, ScramStringFormatting.fromSaslName(s)); } }
@Test public void fromSaslNameWithCharactersToBeUnescaped() { for(int i = 0; i < ESCAPED_VALUES.length; i++) { assertEquals(VALUES_TO_BE_ESCAPED[i], ScramStringFormatting.fromSaslName(ESCAPED_VALUES[i])); } }
@Test public void fromSaslNameWithInvalidCharacters() { int n = 0; for(String s : INVALID_SASL_NAMES) { try { assertEquals(s, ScramStringFormatting.fromSaslName(s)); } catch (IllegalArgumentException e) { n++; } } assertTrue("Not all values produced IllegalArgumentException", n == INVALID_SASL_NAMES.length); } |
ScramFunctions { public static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key) { return CryptoUtil.hmac(scramMechanism.secretKeySpec(key), scramMechanism.getMacInstance(), message); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void hmac() throws UnsupportedEncodingException { String message = "The quick brown fox jumps over the lazy dog"; byte[] key = "key".getBytes(StandardCharsets.UTF_8); assertBytesEqualsBase64( "3nybhbi3iqa8ino29wqQcBydtNk=", ScramFunctions.hmac(ScramMechanisms.SCRAM_SHA_1, message.getBytes(StandardCharsets.US_ASCII), key) ); assertBytesEqualsBase64( "97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg=", ScramFunctions.hmac(ScramMechanisms.SCRAM_SHA_256, message.getBytes(StandardCharsets.US_ASCII), key) ); } |
ScramFunctions { public static byte[] saltedPassword( ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt, int iteration ) { return CryptoUtil.hi( scramMechanism.secretKeyFactory(), scramMechanism.algorithmKeyLength(), stringPreparation.normalize(password), salt, iteration ); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void saltedPassword() { assertBytesEqualsBase64("HZbuOlKbWl+eR8AfIposuKbhX30=", generateSaltedPassword()); } |
ScramFunctions { public static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword) { return hmac(scramMechanism, CLIENT_KEY_HMAC_KEY, saltedPassword); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void clientKey() { assertBytesEqualsBase64("4jTEe/bDZpbdbYUrmaqiuiZVVyg=", generateClientKey()); } |
ScramFunctions { public static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey) { return hash(scramMechanism, clientKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void storedKey() { assertBytesEqualsBase64("6dlGYMOdZcOPutkcNY8U2g7vK9Y=", generateStoredKey()); } |
ScramFunctions { public static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword) { return hmac(scramMechanism, SERVER_KEY_HMAC_KEY, saltedPassword); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void serverKey() { assertBytesEqualsBase64("D+CSWLOshSulAsxiupA+qs2/fTE=", generateServerKey()); } |
ScramFunctions { public static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage) { return hmac(scramMechanism, authMessage.getBytes(StandardCharsets.UTF_8), storedKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void clientSignature() { assertBytesEqualsBase64("XXE4xIawv6vfSePi2ovW5cedthM=", generateClientSignature()); } |
ScramFunctions { public static byte[] clientProof(byte[] clientKey, byte[] clientSignature) { return CryptoUtil.xor(clientKey, clientSignature); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void clientProof() { assertBytesEqualsBase64("v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=", generateClientProof()); } |
ScramFunctions { public static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage) { return clientSignature(scramMechanism, serverKey, authMessage); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void serverSignature() { assertBytesEqualsBase64("rmF9pqV8S7suAoZWja4dJRkFsKQ=", generateServerSignature()); } |
ScramFunctions { public static boolean verifyClientProof( ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage ) { byte[] clientSignature = clientSignature(scramMechanism, storedKey, authMessage); byte[] clientKey = CryptoUtil.xor(clientSignature, clientProof); byte[] computedStoredKey = hash(scramMechanism, clientKey); return Arrays.equals(storedKey, computedStoredKey); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void verifyClientProof() { assertTrue( ScramFunctions.verifyClientProof( ScramMechanisms.SCRAM_SHA_1, generateClientProof(), generateStoredKey(), AUTH_MESSAGE ) ); } |
ScramFunctions { public static boolean verifyServerSignature( ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature ) { return Arrays.equals(serverSignature(scramMechanism, serverKey, authMessage), serverSignature); } static byte[] saltedPassword(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hmac(ScramMechanism scramMechanism, byte[] message, byte[] key); static byte[] clientKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] clientKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] serverKey(ScramMechanism scramMechanism, byte[] saltedPassword); static byte[] serverKey(
ScramMechanism scramMechanism, StringPreparation stringPreparation, String password, byte[] salt,
int iteration
); static byte[] hash(ScramMechanism scramMechanism, byte[] value); static byte[] storedKey(ScramMechanism scramMechanism, byte[] clientKey); static byte[] clientSignature(ScramMechanism scramMechanism, byte[] storedKey, String authMessage); static byte[] clientProof(byte[] clientKey, byte[] clientSignature); static byte[] serverSignature(ScramMechanism scramMechanism, byte[] serverKey, String authMessage); static boolean verifyClientProof(
ScramMechanism scramMechanism, byte[] clientProof, byte[] storedKey, String authMessage
); static boolean verifyServerSignature(
ScramMechanism scramMechanism, byte[] serverKey, String authMessage, byte[] serverSignature
); } | @Test public void verifyServerSignature() { assertTrue( ScramFunctions.verifyServerSignature( ScramMechanisms.SCRAM_SHA_1, generateServerKey(), AUTH_MESSAGE, generateServerSignature() ) ); } |
ScramAttributeValue extends AbstractCharAttributeValue { public static ScramAttributeValue parse(String value) throws ScramParseException { if(null == value || value.length() < 3 || value.charAt(1) != '=') { throw new ScramParseException("Invalid ScramAttributeValue '" + value + "'"); } return new ScramAttributeValue(ScramAttributes.byChar(value.charAt(0)), value.substring(2)); } ScramAttributeValue(ScramAttributes attribute, String value); static StringBuffer writeTo(StringBuffer sb, ScramAttributes attribute, String value); static ScramAttributeValue parse(String value); } | @Test public void parseIllegalValuesStructure() { String[] values = new String[] { null, "", "asdf", "asdf=a", CLIENT_PROOF.getChar() + "=", CLIENT_PROOF.getChar() + ",a" }; int n = 0; for(String value : values) { try { assertNotNull(ScramAttributeValue.parse(value)); } catch(ScramParseException e) { n++; } } assertEquals("Not every illegal value thrown ScramParseException", values.length, n); }
@Test public void parseIllegalValuesInvalidSCRAMAttibute() { String[] values = new String[] { "z=asdfasdf", "!=value" }; int n = 0; for(String value : values) { try { assertNotNull(ScramAttributeValue.parse(value)); } catch(ScramParseException e) { n++; } } assertEquals("Not every illegal value thrown ScramParseException", values.length, n); }
@Test public void parseLegalValues() throws ScramParseException { String[] legalValues = new String[] { CLIENT_PROOF.getChar() + "=" + "proof", USERNAME.getChar() + "=" + "username", "n=" + USER, "r=" + CLIENT_NONCE, "r=" + FULL_NONCE, "s=" + SERVER_SALT, "i=" + SERVER_ITERATIONS, "c=" + GS2_HEADER_BASE64, "p=" + CLIENT_FINAL_MESSAGE_PROOF, SERVER_FINAL_MESSAGE, }; for(String value : legalValues) { assertNotNull(ScramAttributeValue.parse(value)); } for(ServerFinalMessage.Error e : ServerFinalMessage.Error.values()) { assertNotNull(ScramAttributeValue.parse("e=" + e.getErrorMessage())); } } |
Gs2AttributeValue extends AbstractCharAttributeValue { public static Gs2AttributeValue parse(String value) throws IllegalArgumentException { if(null == value) { return null; } if(value.length() < 1 || value.length() == 2 || (value.length() > 2 && value.charAt(1) != '=')) { throw new IllegalArgumentException("Invalid Gs2AttributeValue"); } return new Gs2AttributeValue( Gs2Attributes.byChar(value.charAt(0)), value.length() > 2 ? value.substring(2) : null ); } Gs2AttributeValue(Gs2Attributes attribute, String value); static StringBuffer writeTo(StringBuffer sb, Gs2Attributes attribute, String value); static Gs2AttributeValue parse(String value); } | @Test public void parseNullValue() { assertNull(Gs2AttributeValue.parse(null)); }
@Test public void parseIllegalValuesStructure() { String[] values = new String[] { "", "as", "asdfjkl", Gs2Attributes.CHANNEL_BINDING_REQUIRED.getChar() + "=" }; int n = 0; for(String value : values) { try { assertNotNull(Gs2AttributeValue.parse(value)); } catch(IllegalArgumentException e) { n++; } } assertEquals("Not every illegal value thrown IllegalArgumentException", values.length, n); }
@Test public void parseIllegalValuesInvalidGS2Attibute() { String[] values = new String[] { "z=asdfasdf", "i=value" }; int n = 0; for(String value : values) { try { assertNotNull(Gs2AttributeValue.parse(value)); } catch(IllegalArgumentException e) { n++; } } assertEquals("Not every illegal value thrown IllegalArgumentException", values.length, n); }
@Test public void parseLegalValues() { String[] values = new String[] { "n", "y", "p=value", "a=authzid" }; for(String value : values) { assertNotNull(Gs2AttributeValue.parse(value)); } } |
Gs2Header extends AbstractStringWritable { public static Gs2Header parseFrom(String message) throws IllegalArgumentException { checkNotNull(message, "Null message"); String[] gs2HeaderSplit = StringWritableCsv.parseFrom(message, 2); if(gs2HeaderSplit.length == 0) { throw new IllegalArgumentException("Invalid number of fields for the GS2 Header"); } Gs2AttributeValue gs2cbind = Gs2AttributeValue.parse(gs2HeaderSplit[0]); return new Gs2Header( Gs2CbindFlag.byChar(gs2cbind.getChar()), gs2cbind.getValue(), gs2HeaderSplit[1] == null || gs2HeaderSplit[1].isEmpty() ? null : Gs2AttributeValue.parse(gs2HeaderSplit[1]).getValue() ); } Gs2Header(Gs2CbindFlag cbindFlag, String cbName, String authzid); Gs2Header(Gs2CbindFlag cbindFlag, String cbName); Gs2Header(Gs2CbindFlag cbindFlag); Gs2CbindFlag getChannelBindingFlag(); Optional<String> getChannelBindingName(); Optional<String> getAuthzid(); @Override StringBuffer writeTo(StringBuffer sb); static Gs2Header parseFrom(String message); } | @Test public void parseFromInvalid() { String[] invalids = new String[] { "Z,", "n,Z=blah", "p,", "n=a," }; int n = 0; for(String invalid : invalids) { try { Gs2Header.parseFrom(invalid); System.out.println(invalid); } catch (IllegalArgumentException e) { n++; } } assertEquals(invalids.length, n); } |
ScramClient { public static PreBuilder1 channelBinding(ChannelBinding channelBinding) throws IllegalArgumentException { return new PreBuilder1(checkNotNull(channelBinding, "channelBinding")); } private ScramClient(
ChannelBinding channelBinding, StringPreparation stringPreparation,
Optional<ScramMechanism> nonChannelBindingMechanism, Optional<ScramMechanism> channelBindingMechanism,
SecureRandom secureRandom, Supplier<String> nonceSupplier
); static PreBuilder1 channelBinding(ChannelBinding channelBinding); StringPreparation getStringPreparation(); ScramMechanism getScramMechanism(); static List<String> supportedMechanisms(); ScramSession scramSession(String user); static final int DEFAULT_NONCE_LENGTH; } | @Test public void getValid() { ScramClient client1 = ScramClient .channelBinding(ScramClient.ChannelBinding.NO) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1") .setup(); ScramClient client2 = ScramClient .channelBinding(ScramClient.ChannelBinding.YES) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1", "SCRAM-SHA-256-PLUS") .nonceLength(64) .setup(); ScramClient client3 = ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1", "SCRAM-SHA-1-PLUS") .nonceSupplier(() -> CryptoUtil.nonce(36)) .setup(); ScramClient client4 = ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertisedCsv("SCRAM-SHA-1,SCRAM-SHA-256-PLUS") .secureRandomAlgorithmProvider("SHA1PRNG", "SUN") .nonceLength(64) .setup(); ScramClient client5 = ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertisedCsv("SCRAM-SHA-1,SCRAM-SHA-256-PLUS") .secureRandomAlgorithmProvider("SHA1PRNG", null) .nonceLength(64) .setup(); ScramClient client6 = ScramClient .channelBinding(ScramClient.ChannelBinding.NO) .stringPreparation(StringPreparations.NO_PREPARATION) .selectClientMechanism(ScramMechanisms.SCRAM_SHA_1) .setup(); ScramClient client7 = ScramClient .channelBinding(ScramClient.ChannelBinding.YES) .stringPreparation(StringPreparations.NO_PREPARATION) .selectClientMechanism(ScramMechanisms.SCRAM_SHA_256_PLUS) .setup(); Stream.of(client1, client2, client3, client4, client5, client6, client7).forEach(c -> assertNotNull(c)); }
@Test public void getInvalid() { int n = 0; try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.NO) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1-PLUS") .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.YES) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1-PLUS,SCRAM-SAH-256-PLUS") .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("INVALID-SCRAM-MECHANISM") .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1", "SCRAM-SHA-1-PLUS") .nonceSupplier(null) .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1", "SCRAM-SHA-1-PLUS") .nonceLength(0) .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1", "SCRAM-SHA-1-PLUS") .secureRandomAlgorithmProvider("Invalid algorithm", null) .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectMechanismBasedOnServerAdvertised("SCRAM-SHA-1", "SCRAM-SHA-1-PLUS") .secureRandomAlgorithmProvider("SHA1PRNG", "Invalid provider") .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.YES) .stringPreparation(StringPreparations.NO_PREPARATION) .selectClientMechanism(ScramMechanisms.SCRAM_SHA_1) .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.NO) .stringPreparation(StringPreparations.NO_PREPARATION) .selectClientMechanism(ScramMechanisms.SCRAM_SHA_1_PLUS) .setup() ); } catch (IllegalArgumentException e) { n++; } try { assertNotNull(ScramClient .channelBinding(ScramClient.ChannelBinding.IF_SERVER_SUPPORTS_IT) .stringPreparation(StringPreparations.NO_PREPARATION) .selectClientMechanism(ScramMechanisms.SCRAM_SHA_1) .setup() ); } catch (IllegalArgumentException e) { n++; } assertEquals(10, n); } |
StringWritableCsv { public static String[] parseFrom(String value, int n, int offset) throws IllegalArgumentException { checkNotNull(value, "value"); if(n < 0 || offset < 0) { throw new IllegalArgumentException("Limit and offset have to be >= 0"); } if(value.isEmpty()) { return new String[0]; } String[] split = value.split(","); if(split.length < offset) { throw new IllegalArgumentException("Not enough items for the given offset"); } return Arrays.copyOfRange( split, offset, (n == 0 ? split.length : n) + offset ); } static StringBuffer writeTo(StringBuffer sb, StringWritable... values); static String[] parseFrom(String value, int n, int offset); static String[] parseFrom(String value, int n); static String[] parseFrom(String value); } | @Test public void parseFromEmpty() { assertArrayEquals(new String[]{}, StringWritableCsv.parseFrom("")); }
@Test public void parseFromOneArgWithLimitsOffsets() { for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] {s}, StringWritableCsv.parseFrom(s)); } int[] numberEntries = new int[] { 0, 1 }; for(int n : numberEntries) { for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] {s}, StringWritableCsv.parseFrom(s, n)); } } for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] {s, null, null}, StringWritableCsv.parseFrom(s, 3)); } for(int n : numberEntries) { for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] {s}, StringWritableCsv.parseFrom(s, n, 0)); } } for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] {s, null, null}, StringWritableCsv.parseFrom(s, 3, 0)); } for(int n : numberEntries) { for(String s : ONE_ARG_VALUES) { assertArrayEquals(new String[] { null }, StringWritableCsv.parseFrom(s, n, 1)); } } }
@Test public void parseFromSeveralArgsWithLimitsOffsets() { assertArrayEquals( new String[] { "n", "", "n=user", "r=fyko+d2lbbFgONRv9qkxdawL" }, StringWritableCsv.parseFrom(SEVERAL_VALUES_STRING) ); assertArrayEquals( new String[] { "n", "" }, StringWritableCsv.parseFrom(SEVERAL_VALUES_STRING, 2) ); assertArrayEquals( new String[] { "", "n=user" }, StringWritableCsv.parseFrom(SEVERAL_VALUES_STRING, 2, 1) ); assertArrayEquals( new String[] { "r=fyko+d2lbbFgONRv9qkxdawL", null }, StringWritableCsv.parseFrom(SEVERAL_VALUES_STRING, 2, 3) ); assertArrayEquals( new String[] { null, null }, StringWritableCsv.parseFrom(SEVERAL_VALUES_STRING, 2, 4) ); assertArrayEquals( new String[] { "n", "", "n=user", "r=fyko+d2lbbFgONRv9qkxdawL", null }, StringWritableCsv.parseFrom(SEVERAL_VALUES_STRING, 5) ); } |
ScramClient { public static List<String> supportedMechanisms() { return Arrays.stream(ScramMechanisms.values()).map(m -> m.getName()).collect(Collectors.toList()); } private ScramClient(
ChannelBinding channelBinding, StringPreparation stringPreparation,
Optional<ScramMechanism> nonChannelBindingMechanism, Optional<ScramMechanism> channelBindingMechanism,
SecureRandom secureRandom, Supplier<String> nonceSupplier
); static PreBuilder1 channelBinding(ChannelBinding channelBinding); StringPreparation getStringPreparation(); ScramMechanism getScramMechanism(); static List<String> supportedMechanisms(); ScramSession scramSession(String user); static final int DEFAULT_NONCE_LENGTH; } | @Test public void supportedMechanismsTestAll() { assertArrayEquals( Arrays.stream( new String[] { "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS" } ).sorted().toArray(), ScramClient.supportedMechanisms().stream().sorted().toArray() ); } |
CryptoUtil { public static String nonce(int size, SecureRandom random) { if(size <= 0) { throw new IllegalArgumentException("Size must be positive"); } char[] chars = new char[size]; int r; for(int i = 0; i < size;) { r = random.nextInt(MAX_ASCII_PRINTABLE_RANGE - MIN_ASCII_PRINTABLE_RANGE + 1) + MIN_ASCII_PRINTABLE_RANGE; if(r != EXCLUDED_CHAR) { chars[i++] = (char) r; } } return new String(chars); } static String nonce(int size, SecureRandom random); static String nonce(int size); static byte[] hi(
SecretKeyFactory secretKeyFactory, int keyLength, String value, byte[] salt, int iterations
); static byte[] hmac(SecretKeySpec secretKeySpec, Mac mac, byte[] message); static byte[] xor(byte[] value1, byte[] value2); } | @Test(expected = IllegalArgumentException.class) public void nonceInvalidSize1() { CryptoUtil.nonce(0, SECURE_RANDOM); }
@Test(expected = IllegalArgumentException.class) public void nonceInvalidSize2() { CryptoUtil.nonce(-1, SECURE_RANDOM); }
@Test public void nonceValid() { int nNonces = 1000; int nonceMaxSize = 100; Random random = new Random(); for(int i = 0; i < nNonces; i++) { for(char c : CryptoUtil.nonce(random.nextInt(nonceMaxSize) + 1, SECURE_RANDOM).toCharArray()) { if(c == ',' || c < (char) 33 || c > (char) 126) { fail("Character c='" + c + "' is not allowed on a nonce"); } } } } |
YAMLFileParameterizer { protected static String normalizeFilename(String filename) { return StringUtils.trimToEmpty(filename).replaceAll("\\\\|/", "\\"+File.separator); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> generateEnvVars); static void rewriteFiles(File sourceDir, File destDir, Map<String, Any> generateEnvVars); static void rewriteResources(String resourceLocation, String destDir, Map<String, Any> generateEnvVars); static void copyResources(String resourceLocation, String destDir); static void rewriteResource(String filename, String resourceLocation, String destFilename, Map<String, Any> generateEnvVars); static void rewriteFile(File srcFile, File destFile, Map<String, Any> generateEnvVars); static String toNonNullString(URL url); static String getAbsolutePath(File f); static final String GENERATE_ENV_VARS; static final String CLASS_PATH_PREFIX; static final String DEFAULT_RESOURCE_LOCATION; static final String DEFAULT_DEST_DIR; } | @Test public void testNormalizeFilename() { String s1="/a/b/c\\d.txt"; String s2="\\a\\b\\c\\d.txt"; String expected = String.format("%sa%sb%sc%sd.txt", File.separator, File.separator, File.separator, File.separator); String ns1 = YAMLFileParameterizer.normalizeFilename(s1); String ns2 = YAMLFileParameterizer.normalizeFilename(s2); assertTrue(expected.equals(ns1)); assertTrue(expected.equals(ns2)); } |
HybridServiceGenerator implements Generator { @Override public String getFramework() { return "light-hybrid-4j-service"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGetFramework() { HybridServiceGenerator generator = new HybridServiceGenerator(); Assert.assertEquals("light-hybrid-4j-service", generator.getFramework()); } |
HybridServerGenerator implements Generator { @Override public void generate(String targetPath, Object model, Any config) throws IOException { String rootPackage = config.get("rootPackage").toString(); String modelPackage = config.get("modelPackage").toString(); String handlerPackage = config.get("handlerPackage").toString(); boolean enableHttp = config.toBoolean("enableHttp"); String httpPort = config.toString("httpPort"); boolean enableHttps = config.toBoolean("enableHttps"); String httpsPort = config.toString("httpsPort"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean eclipseIDE = config.toBoolean("eclipseIDE"); String dockerOrganization = config.toString("dockerOrganization"); String artifactId = config.toString("artifactId"); String version = config.toString("version"); if(dockerOrganization == null || dockerOrganization.length() == 0) dockerOrganization = "networknt"; boolean supportClient = config.toBoolean("supportClient"); String serviceId = config.get("groupId").toString().trim() + "." + artifactId.trim() + "-" + config.get("version").toString().trim(); boolean prometheusMetrics = config.toBoolean("prometheusMetrics"); boolean skipHealthCheck = config.toBoolean("skipHealthCheck"); boolean skipServerInfo = config.toBoolean("skipServerInfo"); String jsonPath = config.get("jsonPath").toString(); boolean kafkaProducer = config.toBoolean("kafkaProducer"); boolean kafkaConsumer = config.toBoolean("kafkaConsumer"); boolean supportAvro = config.toBoolean("supportAvro"); String kafkaTopic = config.get("kafkaTopic").toString(); transfer(targetPath, "", "pom.xml", templates.hybrid.server.pom.template(config)); transferMaven(targetPath); String expose = ""; if(enableHttps) { expose = httpsPort; } else { expose = httpPort; } transfer(targetPath, "docker", "Dockerfile", templates.hybrid.server.dockerfile.template(config, expose)); transfer(targetPath, "docker", "Dockerfile-Slim", templates.hybrid.server.dockerfileslim.template(config, expose)); transfer(targetPath, "", "build.sh", templates.hybrid.server.buildSh.template(dockerOrganization, config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"))); transfer(targetPath, "", ".gitignore", templates.hybrid.gitignore.template()); transfer(targetPath, "", "README.md", templates.hybrid.server.README.template()); transfer(targetPath, "", "LICENSE", templates.hybrid.LICENSE.template()); if(eclipseIDE) { transfer(targetPath, "", ".classpath", templates.hybrid.classpath.template()); transfer(targetPath, "", ".project", templates.hybrid.project.template()); } transfer(targetPath, ("src.main.resources.config").replace(".", separator), "service.yml", templates.hybrid.serviceYml.template(config)); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "server.yml", templates.hybrid.serverYml.template(config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, httpPort, enableHttps, httpsPort, enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.hybrid.serverYml.template(config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); if(kafkaProducer) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "kafka-producer.yml", templates.hybrid.kafkaProducerYml.template(kafkaTopic)); } if(kafkaConsumer) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "kafka-streams.yml", templates.hybrid.kafkaStreamsYml.template(artifactId)); } if(supportAvro) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "schema-registry.yml", templates.hybrid.schemaRegistryYml.template()); } transfer(targetPath, ("src.main.resources.config").replace(".", separator), "hybrid-security.yml", templates.hybrid.securityYml.template()); if(supportClient) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "client.yml", templates.hybrid.clientYml.template()); } else { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.hybrid.clientYml.template()); } transfer(targetPath, ("src.main.resources.config").replace(".", separator), "primary.crt", templates.hybrid.primaryCrt.template()); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "secondary.crt", templates.hybrid.secondaryCrt.template()); transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.hybrid.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.hybrid.logback.template()); try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } if(supportClient) { try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "client.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "client.truststore"), StandardCopyOption.REPLACE_EXISTING); } } else { try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "client.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "client.truststore"), StandardCopyOption.REPLACE_EXISTING); } } transfer(targetPath, ("src.main.resources.config").replace(".", separator), "handler.yml", templates.hybrid.handlerYml.template(serviceId, handlerPackage, jsonPath, prometheusMetrics, !skipHealthCheck, !skipServerInfo)); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "rpc-router.yml", templates.hybrid.rpcRouterYml.template(handlerPackage, jsonPath)); } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGenerator() throws IOException { Any anyConfig = JsonIterator.parse(HybridServerGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); HybridServerGenerator generator = new HybridServerGenerator(); generator.generate(targetPath, null, anyConfig); } |
HybridServerGenerator implements Generator { @Override public String getFramework() { return "light-hybrid-4j-server"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGetFramework() { HybridServerGenerator generator = new HybridServerGenerator(); Assert.assertEquals("light-hybrid-4j-server", generator.getFramework()); } |
GraphqlGenerator implements Generator { @Override public void generate(String targetPath, Object model, Any config) throws IOException { String schemaPackage = config.get("schemaPackage").toString(); String schemaClass = config.get("schemaClass").toString(); boolean overwriteSchemaClass = config.toBoolean("overwriteSchemaClass"); boolean enableHttp = config.toBoolean("enableHttp"); String httpPort = config.toString("httpPort"); boolean enableHttps = config.toBoolean("enableHttps"); String httpsPort = config.toString("httpsPort"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean eclipseIDE = config.toBoolean("eclipseIDE"); boolean supportClient = config.toBoolean("supportClient"); boolean prometheusMetrics = config.toBoolean("prometheusMetrics"); boolean skipHealthCheck = config.toBoolean("skipHealthCheck"); boolean skipServerInfo = config.toBoolean("skipServerInfo"); String dockerOrganization = config.toString("dockerOrganization"); String version = config.toString("version"); String serviceId = config.get("groupId").toString().trim() + "." + config.get("artifactId").toString().trim() + "-" + config.get("version").toString().trim(); if(dockerOrganization == null || dockerOrganization.length() == 0) dockerOrganization = "networknt"; transfer(targetPath, "", "pom.xml", templates.graphql.pom.template(config)); transferMaven(targetPath); String expose = ""; if(enableHttps) { expose = httpsPort; } else { expose = httpPort; } transfer(targetPath, "docker", "Dockerfile", templates.graphql.dockerfile.template(config, expose)); transfer(targetPath, "docker", "Dockerfile-Slim", templates.graphql.dockerfileslim.template(config, expose)); transfer(targetPath, "", "build.sh", templates.graphql.buildSh.template(dockerOrganization, config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"))); transfer(targetPath, "", ".gitignore", templates.graphql.gitignore.template()); transfer(targetPath, "", "README.md", templates.graphql.README.template()); transfer(targetPath, "", "LICENSE", templates.graphql.LICENSE.template()); if(eclipseIDE) { transfer(targetPath, "", ".classpath", templates.graphql.classpath.template()); transfer(targetPath, "", ".project", templates.graphql.project.template()); } transfer(targetPath, ("src.main.resources.config").replace(".", separator), "service.yml", templates.graphql.serviceYml.template(config)); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "server.yml", templates.graphql.serverYml.template(config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, httpPort, enableHttps, httpsPort, enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.graphql.serverYml.template(config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "secret.yml", templates.graphql.secretYml.template()); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "graphql-security.yml", templates.graphql.securityYml.template()); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "graphql-validator.yml", templates.graphql.validatorYml.template()); if(supportClient) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "client.yml", templates.graphql.clientYml.template()); } else { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.graphql.clientYml.template()); } transfer(targetPath, ("src.main.resources.config").replace(".", separator), "primary.crt", templates.graphql.primaryCrt.template()); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "secondary.crt", templates.graphql.secondaryCrt.template()); transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.graphql.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.graphql.logback.template()); transfer(targetPath, ("src.main.resources.config").replace(".", separator), "handler.yml", templates.graphql.handlerYml.template(serviceId, prometheusMetrics, !skipHealthCheck, !skipServerInfo)); if(overwriteSchemaClass) { if(model == null) { transfer(targetPath, ("src.main.java." + schemaPackage).replace(".", separator), schemaClass + ".java", templates.graphql.schemaClassExample.template(schemaPackage, schemaClass)); } else { Files.write(FileSystems.getDefault().getPath(targetPath, ("src.main.resources").replace(".", separator), "schema.graphqls"), ((String)model).getBytes(StandardCharsets.UTF_8)); transfer(targetPath, ("src.main.java." + schemaPackage).replace(".", separator), schemaClass + ".java", templates.graphql.schemaClass.template(schemaPackage, schemaClass)); } } try (InputStream is = GraphqlGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = GraphqlGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } if(supportClient) { try (InputStream is = GraphqlGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "client.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = GraphqlGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.main.resources.config").replace(".", separator), "client.truststore"), StandardCopyOption.REPLACE_EXISTING); } } else { try (InputStream is = GraphqlGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "client.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = GraphqlGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "client.truststore"), StandardCopyOption.REPLACE_EXISTING); } } } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGeneratorWithSchema() throws IOException { Any anyConfig = JsonIterator.parse(GraphqlGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); try(InputStream is = GraphqlGenerator.class.getResourceAsStream(schemaName)) { String schema = convertStreamToString(is); GraphqlGenerator generator = new GraphqlGenerator(); generator.generate(targetPath, schema, anyConfig); } }
@Test public void testGeneratorWithoutSchema() throws IOException { Any anyConfig = JsonIterator.parse(GraphqlGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); GraphqlGenerator generator = new GraphqlGenerator(); generator.generate(targetPath, null, anyConfig); } |
GraphqlGenerator implements Generator { @Override public String getFramework() { return "light-graphql-4j"; } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGetFramework() { GraphqlGenerator generator = new GraphqlGenerator(); Assert.assertEquals("light-graphql-4j", generator.getFramework()); } |
YAMLFileParameterizer { protected static Set<String> buildFileExcludeSet(String sourceDir, Map<String, Any> generateEnvVars) { if (generateEnvVars.containsKey(KEY_EXCLUDE)) { return buildFileExcludeSet(sourceDir, generateEnvVars.get(KEY_EXCLUDE).asList()); } return Collections.emptySet(); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> generateEnvVars); static void rewriteFiles(File sourceDir, File destDir, Map<String, Any> generateEnvVars); static void rewriteResources(String resourceLocation, String destDir, Map<String, Any> generateEnvVars); static void copyResources(String resourceLocation, String destDir); static void rewriteResource(String filename, String resourceLocation, String destFilename, Map<String, Any> generateEnvVars); static void rewriteFile(File srcFile, File destFile, Map<String, Any> generateEnvVars); static String toNonNullString(URL url); static String getAbsolutePath(File f); static final String GENERATE_ENV_VARS; static final String CLASS_PATH_PREFIX; static final String DEFAULT_RESOURCE_LOCATION; static final String DEFAULT_DEST_DIR; } | @Test public void testFileExcludeSet() { List<Any> excludes = Arrays.asList(Any.wrap("/a/b/c\\d.txt"), Any.wrap("2.yml"), Any.wrap("\\a\\b\\c\\d.txt"), Any.wrap("")); Set<String> excludeSet = YAMLFileParameterizer.buildFileExcludeSet(".",excludes); assertTrue(2==excludeSet.size()); } |
YAMLFileParameterizer { protected static Set<String> buildResourceExcludeSet(String resourceLocation, Map<String, Any> generateEnvVars) { if (generateEnvVars.containsKey(KEY_EXCLUDE)) { return buildResourceExcludeSet(resourceLocation, generateEnvVars.get(KEY_EXCLUDE).asList()); } return Collections.emptySet(); } static void rewriteAll(String dir, Map<String, Any> generateEnvVars); static void rewriteAll(String srcLocation, String destDir, Map<String, Any> generateEnvVars); static void rewriteFiles(File sourceDir, File destDir, Map<String, Any> generateEnvVars); static void rewriteResources(String resourceLocation, String destDir, Map<String, Any> generateEnvVars); static void copyResources(String resourceLocation, String destDir); static void rewriteResource(String filename, String resourceLocation, String destFilename, Map<String, Any> generateEnvVars); static void rewriteFile(File srcFile, File destFile, Map<String, Any> generateEnvVars); static String toNonNullString(URL url); static String getAbsolutePath(File f); static final String GENERATE_ENV_VARS; static final String CLASS_PATH_PREFIX; static final String DEFAULT_RESOURCE_LOCATION; static final String DEFAULT_DEST_DIR; } | @Test public void testResourceExcludeSet() { List<Any> excludes = Arrays.asList(Any.wrap("audit.yml"), Any.wrap("body.yml")); Set<String> excludeSet = YAMLFileParameterizer.buildResourceExcludeSet("handlerconfig/", excludes); assertTrue(2==excludeSet.size()); } |
OpenApiSpecGenerator implements Generator { @SuppressWarnings("rawtypes") @Override public void generate(String targetPath, Object model, Any config) throws IOException { if (StringUtils.isBlank(targetPath)) { logger.error("Output location is not specified."); return; } if (!config.keys().contains(CONFIG_SPECGENERATION)) { logger.error("Missing config: cannot find {} in the specified config file", CONFIG_SPECGENERATION); return; } Map<String, Any> genConfig = config.get(CONFIG_SPECGENERATION).asMap(); String modelPackages = StringUtils.trimToEmpty(genConfig.get(CONFIG_MODELPACKAGES).toString()); String mergeTo = StringUtils.trimToEmpty(genConfig.get(CONFIG_MERGETO).toString()); String outputFormat = StringUtils.trimToEmpty(genConfig.get(CONFIG_OUTPUTFORMAT).toString()); String outputFilename = StringUtils.trimToEmpty(genConfig.get(CONFIG_OUTPUTFILENAME).toString()); File output_dir = new File(targetPath); if (!output_dir.exists() || !output_dir.isDirectory()) { output_dir.mkdirs(); } String[] basePackageArray = modelPackages.split(COMMA_SPACE); Map<String, Schema> schemas = new HashMap<>(); for (String packageName: basePackageArray) { try (ScanResult scanResult = new ClassGraph() .enableClassInfo() .whitelistPackages(packageName) .scan()) { List<Class<?>> classes = scanResult.getAllClasses().loadClasses(); for (Class<?> cls: classes) { schemas.putAll(ModelConverters.getInstance().read(cls)); } } } OpenAPI openApi = new OpenAPI(); openApi.setComponents(new Components().schemas(schemas)); openApi = merge(openApi, mergeTo); String[] formats = outputFormat.split(COMMA_SPACE); String filename = StringUtils.isBlank(outputFilename)?DEFAULT_OUTPUT_NAME:outputFilename; for (String format: formats) { dump(openApi, format, new File(output_dir, filename + DOT + format)); } } @Override String getFramework(); @SuppressWarnings("rawtypes") @Override void generate(String targetPath, Object model, Any config); } | @Test public void test() throws IOException { Any anyConfig = JsonIterator.parse(OpenApiGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); OpenApiSpecGenerator generator = new OpenApiSpecGenerator(); generator.generate(outputDir, null, anyConfig); } |
Utils { public static String camelize(String word) { return camelize(word, false); } static String camelize(String word); static String camelize(String word, boolean lowercaseFirstLetter); static boolean isUrl(String location); static byte[] urlToByteArray(URL url); } | @Test public void testUnderscoreToLowerCamel() { for (Map.Entry<String, String> entry : underscoreToLowerCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey(), true)); } }
@Test public void testUnderscoreToCamel() { for (Map.Entry<String, String> entry : underscoreToCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey())); } }
@Test public void testSlashToCamel() { for (Map.Entry<String, String> entry : slashToCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey())); } }
@Test public void testCamelToUnderscore() { for (Map.Entry<String, String> entry : camelToUnderscore_.entrySet()) { Assert.assertEquals(entry.getKey(), Utils.camelize(entry.getValue())); } }
@Test public void testDashToCamel() { for (Map.Entry<String, String> entry : dashToCamel_.entrySet()) { Assert.assertEquals(entry.getValue(), Utils.camelize(entry.getKey())); } } |
HybridServiceGenerator implements Generator { @Override public void generate(String targetPath, Object model, Any config) throws IOException { String handlerPackage = config.get("handlerPackage").toString(); boolean overwriteHandler = config.toBoolean("overwriteHandler"); boolean overwriteHandlerTest = config.toBoolean("overwriteHandlerTest"); boolean enableHttp = config.toBoolean("enableHttp"); boolean enableHttps = config.toBoolean("enableHttps"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean eclipseIDE = config.toBoolean("eclipseIDE"); boolean supportClient = config.toBoolean("supportClient"); String artifactId = config.toString("artifactId"); String version = config.toString("version"); String serviceId = config.get("groupId").toString().trim() + "." + artifactId.trim() + "-" + config.get("version").toString().trim(); boolean prometheusMetrics = config.toBoolean("prometheusMetrics"); boolean skipHealthCheck = config.toBoolean("skipHealthCheck"); boolean skipServerInfo = config.toBoolean("skipServerInfo"); String jsonPath = config.get("jsonPath").toString(); boolean kafkaProducer = config.toBoolean("kafkaProducer"); boolean kafkaConsumer = config.toBoolean("kafkaConsumer"); boolean supportAvro = config.toBoolean("supportAvro"); String kafkaTopic = config.get("kafkaTopic").toString(); transfer(targetPath, "", "pom.xml", templates.hybrid.service.pom.template(config)); transferMaven(targetPath); transfer(targetPath, "", ".gitignore", templates.hybrid.gitignore.template()); transfer(targetPath, "", "README.md", templates.hybrid.service.README.template()); transfer(targetPath, "", "LICENSE", templates.hybrid.LICENSE.template()); if(eclipseIDE) { transfer(targetPath, "", ".classpath", templates.hybrid.classpath.template()); transfer(targetPath, "", ".project", templates.hybrid.project.template()); } transfer(targetPath, ("src.test.resources.config").replace(".", separator), "service.yml", templates.hybrid.serviceYml.template(config)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.hybrid.serverYml.template(config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "hybrid-security.yml", templates.hybrid.securityYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.hybrid.clientYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "primary.crt", templates.hybrid.primaryCrt.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secondary.crt", templates.hybrid.secondaryCrt.template()); if(kafkaProducer) { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "kafka-producer.yml", templates.hybrid.kafkaProducerYml.template(kafkaTopic)); } if(kafkaConsumer) { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "kafka-streams.yml", templates.hybrid.kafkaStreamsYml.template(artifactId)); } if(supportAvro) { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "schema-registry.yml", templates.hybrid.schemaRegistryYml.template()); } transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.hybrid.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.hybrid.logback.template()); Map<String, Object> services = new HashMap<String, Object>(); Any anyModel = (Any)model; String host = anyModel.toString("host"); String service = anyModel.toString("service"); List<Any> items = anyModel.get("action").asList(); if(items != null && items.size() > 0) { for(Any item : items) { Any any = item.get("example"); String example = any.valueType() != ValueType.INVALID ? StringEscapeUtils.escapeJson(any.toString()).trim() : ""; if(!overwriteHandler && checkExist(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java")) { continue; } transfer(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java", templates.hybrid.handler.template(handlerPackage, host, service, item, example)); String sId = host + "/" + service + "/" + item.get("name") + "/" + item.get("version"); Map<String, Object> map = new HashMap<>(); map.put("schema", item.get("schema")); Any anyScope = item.get("scope"); String scope = anyScope.valueType() != ValueType.INVALID ? anyScope.toString().trim() : null; if(scope != null) map.put("scope", scope); Any anySkipAuth = item.get("skipAuth"); Boolean skipAuth = anySkipAuth.valueType() != ValueType.INVALID ? anySkipAuth.toBoolean() : null; if(skipAuth != null) map.put("skipAuth", skipAuth); services.put(sId, map); } transfer(targetPath, ("src.test.java." + handlerPackage + ".").replace(".", separator), "TestServer.java", templates.hybrid.testServer.template(handlerPackage)); for(Any item : items) { if(!overwriteHandlerTest && checkExist(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java")) { continue; } transfer(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java", templates.hybrid.handlerTest.template(handlerPackage, host, service, item)); } } try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/client.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "client.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/client.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "client.truststore"), StandardCopyOption.REPLACE_EXISTING); } if(Files.notExists(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator)))) { Files.createDirectories(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator))); } transfer(targetPath, ("src.test.resources.config").replace(".", separator), "handler.yml", templates.hybrid.handlerYml.template(serviceId, handlerPackage, jsonPath, prometheusMetrics, !skipHealthCheck, !skipServerInfo)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "rpc-router.yml", templates.hybrid.rpcRouterYml.template(handlerPackage, jsonPath)); JsonStream.serialize(services, new FileOutputStream(FileSystems.getDefault().getPath(targetPath, ("src.main.resources").replace(".", separator), "schema.json").toFile())); } @Override String getFramework(); @Override void generate(String targetPath, Object model, Any config); } | @Test public void testGenerator() throws IOException { Any anyConfig = JsonIterator.parse(HybridServiceGeneratorTest.class.getResourceAsStream(configName), 1024).readAny(); Any anyModel = JsonIterator.parse(HybridServiceGeneratorTest.class.getResourceAsStream(schemaName), 1024).readAny(); HybridServiceGenerator generator = new HybridServiceGenerator(); generator.generate(targetPath, anyModel, anyConfig); } |
Token { public static boolean isValid(final String token) { if (token == null || token.length() == 0) { return false; } final int len = token.length(); for (int i = 0; i < len; ++i) { if (isSeparator(token.charAt(i))) { return false; } } return true; } static boolean isSeparator(final char ch); static boolean isValid(final String token); static String unescape(final String text); static String unquote(String text); } | @Test public void test004() { isValid("abc"); } |
Accept extends AbstractFrameFilter implements FrameFilter { @Override public boolean process(TransactionContext context) { if (expression != null) { String resolvedExpression = Template.preProcess(expression, getContext().getSymbols()); try { if (evaluator.evaluateBoolean(resolvedExpression)) { if (Log.isLogging(Log.DEBUG_EVENTS)) { Log.debug("Accepted frame " + context.getRow()); } return false; } else { if (Log.isLogging(Log.DEBUG_EVENTS)) { Log.debug("Did not pass accept expression of '" + resolvedExpression + "'"); } } } catch (IllegalArgumentException e) { Log.warn(LogMsg.createMsg(CDX.MSG, "Filter.accept_boolean_evaluation_error", e.getMessage())); } } return true; } Accept(); Accept(String condition); @Override boolean process(TransactionContext context); } | @Test public void testAcceptContext() { Accept filter = new Accept(); String expression = "match( Working.Record Type , PO )"; filter.setCondition(expression); filter.open(transformContext); assertFalse(filter.process(context)); assertNotNull(context.getWorkingFrame()); } |
TransformContext extends OperationalContext { public Object resolveFieldValue(final String token) { Object retval = null; if (token.startsWith(WORKING)) { final String name = token.substring(WORKING.length()); if ((transactionContext != null) && (transactionContext.getWorkingFrame() != null)) { retval = transactionContext.getWorkingFrame().getObject(name); } } else if (token.startsWith(SOURCE)) { final String name = token.substring(SOURCE.length()); if ((transactionContext != null) && (transactionContext.getSourceFrame() != null)) { retval = transactionContext.getSourceFrame().getObject(name); } } else if (token.startsWith(TARGET)) { final String name = token.substring(TARGET.length()); if ((transactionContext != null) && (transactionContext.getTargetFrame() != null)) { retval = transactionContext.getTargetFrame().getObject(name); } } else if (token.startsWith(CONTEXT)) { final String name = token.substring(CONTEXT.length()); if (transactionContext != null) { retval = transactionContext.get(name); } } else if (token.startsWith(TRANSFORM)) { final String name = token.substring(TRANSFORM.length()); retval = get(name); } return retval; } TransformContext(); TransformContext(final List<ContextListener> listeners); void close(); boolean containsField(final String token); Config getConfiguration(); TransactionContext getTransaction(); @SuppressWarnings("unchecked") void open(); void reset(); String resolveArgument(final String value); String resolveField(final String token); Object resolveFieldValue(final String token); String resolveToString(final String token); Object resolveToValue(final String token); void setConfiguration(final Config config); void setEngine(final TransformEngine engine); void setTransaction(final TransactionContext context); TransformEngine getEngine(); static final String DISPOSITION; static final String ENDTIME; static final String ERROR_MSG; static final String ERROR_STATE; static final String FRAME_COUNT; static final String STARTTIME; } | @Test public void resolveFieldValue() { assertNull(transformContext.resolveFieldValue("one")); assertNotNull(transformContext.resolveFieldValue("Source.Field2")); assertNotNull(transformContext.resolveFieldValue("Working.Field4")); assertNotNull(transformContext.resolveFieldValue("Target.Field6")); assertNull(transformContext.resolveFieldValue("field3")); } |
TransformContext extends OperationalContext { public Object resolveToValue(final String token) { Object retval = null; if (StringUtil.isNotEmpty(token)) { final Object value = resolveFieldValue(token); if (value != null) { retval = value; } else { final Object obj = searchForValue(token); if (obj != null) { retval = obj; } else { if (symbols != null && symbols.containsKey(token)) { retval = symbols.get(token); } } } } return retval; } TransformContext(); TransformContext(final List<ContextListener> listeners); void close(); boolean containsField(final String token); Config getConfiguration(); TransactionContext getTransaction(); @SuppressWarnings("unchecked") void open(); void reset(); String resolveArgument(final String value); String resolveField(final String token); Object resolveFieldValue(final String token); String resolveToString(final String token); Object resolveToValue(final String token); void setConfiguration(final Config config); void setEngine(final TransformEngine engine); void setTransaction(final TransactionContext context); TransformEngine getEngine(); static final String DISPOSITION; static final String ENDTIME; static final String ERROR_MSG; static final String ERROR_STATE; static final String FRAME_COUNT; static final String STARTTIME; } | @Test public void resolveToValue() { assertNull(transformContext.resolveFieldValue("one")); assertNotNull(transformContext.resolveFieldValue("Source.Field2")); assertNotNull(transformContext.resolveFieldValue("Working.Field4")); assertNotNull(transformContext.resolveFieldValue("Target.Field6")); assertNull(transformContext.resolveToValue("nested")); assertNotNull(transformContext.resolveToValue("Nested")); assertNotNull(transformContext.resolveToValue("Nested.bird")); assertNotNull(transformContext.resolveToValue("Map.legend")); assertNotNull(transformContext.resolveToValue("Map.path.secret")); } |
FileContext extends PersistentContext { public FileContext() { } FileContext(); @Override void open(); @Override void close(); } | @Test public void fileContext() { String jobName = "ContextTest"; DataFrame config = new DataFrame().set("fields", new DataFrame().set("SomeKey", "SomeValue").set("AnotherKey", "AnotherValue")); TransformEngine engine = new DefaultTransformEngine(); engine.setName(jobName); TransformContext context = new FileContext(); context.setConfiguration(new Config(config)); engine.setContext(context); turnOver(engine); Object obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long runcount = (Long)obj; assertTrue(runcount > 0); SymbolTable symbols = engine.getSymbolTable(); obj = symbols.get(Symbols.CURRENT_RUN_MILLIS); assertTrue(obj instanceof Long); long millis = (Long)obj; obj = symbols.get(Symbols.CURRENT_RUN_SECONDS); assertTrue(obj instanceof Long); long seconds = (Long)obj; assertTrue(seconds == (millis / 1000)); turnOver(engine); obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long nextRunCount = (Long)obj; assertEquals(runcount + 1, nextRunCount); context = new FileContext(); context.setConfiguration(new Config(config)); engine.setContext(context); turnOver(engine); obj = context.get(Symbols.RUN_COUNT); assertTrue(obj instanceof Long); long lastRunCount = (Long)obj; assertEquals(nextRunCount + 1, lastRunCount); } |
NotEmpty extends AbstractValidator implements FrameValidator { @Override public boolean process(TransactionContext context) throws ValidationException { boolean retval = true; DataFrame frame = context.getWorkingFrame(); if (frame != null) { DataField field = frame.getField(fieldName); if (field != null) { String value = field.getStringValue(); if (StringUtil.isBlank(value)) { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName, "There is no working frame"); } return retval; } NotEmpty(); @Override boolean process(TransactionContext context); } | @Test public void test() { String cfgData = "{ \"field\" : \"model\", \"desc\" : \"Model cannot be empty\" }"; Config configuration = parseConfiguration(cfgData); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("model", "PT4500"); context.setSourceFrame(sourceFrame); try (FrameValidator validator = new NotEmpty()) { validator.setConfiguration(configuration); validator.open(getTransformContext()); boolean result = validator.process(context); assertTrue(result); sourceFrame = new DataFrame(); sourceFrame.put("model", " "); context.setSourceFrame(sourceFrame); result = validator.process(context); assertFalse(result); } catch (ConfigurationException | ValidationException | IOException e) { e.printStackTrace(); fail(e.getMessage()); } } |
NotNull extends AbstractValidator implements FrameValidator { @Override public boolean process(TransactionContext context) throws ValidationException { boolean retval = true; DataFrame frame = context.getWorkingFrame(); if (frame != null) { DataField field = frame.getField(fieldName); if (field != null) { if (field.isNull()) { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName); } } else { retval = false; fail(context, fieldName, "There is no working frame"); } return retval; } NotNull(); @Override boolean process(TransactionContext context); } | @Test public void test() { String cfgData = "{ \"field\" : \"model\", \"desc\" : \"Model cannot be empty\" }"; Config configuration = parseConfiguration(cfgData); FrameValidator validator = new NotNull(); try { validator.setConfiguration(configuration); } catch (ConfigurationException e) { e.printStackTrace(); fail(e.getMessage()); } validator.open(getTransformContext()); TransactionContext context = createTransactionContext(); DataFrame sourceFrame = new DataFrame(); sourceFrame.put("model", "PT4500"); context.setSourceFrame(sourceFrame); try { boolean result = validator.process(context); assertTrue(result); } catch (ValidationException e) { e.printStackTrace(); fail(e.getMessage()); } context = createTransactionContext(); sourceFrame = new DataFrame(); sourceFrame.put("model", " "); context.setSourceFrame(sourceFrame); try { boolean result = validator.process(context); assertTrue(result); } catch (ValidationException e) { e.printStackTrace(); fail(e.getMessage()); } context = createTransactionContext(); sourceFrame = new DataFrame(); sourceFrame.put("model", null); context.setSourceFrame(sourceFrame); try { boolean result = validator.process(context); assertFalse(result); } catch (ValidationException e) { e.printStackTrace(); fail(e.getMessage()); } } |
Pagination { public synchronized void step() { offset += step; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); } | @Test public void testStep() { Pagination page = new Pagination(5); assertEquals("page", page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); assertTrue(page.getOffset() == 5); } |
Pagination { public synchronized void reset() { this.offset = start; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); } | @Test public void testReset() { final String NAME = "offset"; Pagination page = new Pagination(NAME, 5); assertEquals(NAME, page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); page.step(); page.step(); page.step(); page.step(); page.step(); assertTrue(page.getOffset() == 30); assertTrue(page.getEnd() == 35); page.reset(); assertTrue(page.getOffset() == 0); assertTrue(page.getEnd() == 5); } |
Pagination { @SuppressWarnings("unchecked") public synchronized SymbolTable toSymbolTable() { SymbolTable retval = new SymbolTable(); retval.put(name + ".start", getOffset()); retval.put(name + ".size", getStep()); retval.put(name + ".end", getEnd()); return retval; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); } | @Test public void testToSymbolTable() { final String NAME = "offset"; Pagination page = new Pagination(NAME, 0, 5); assertEquals(NAME, page.getName()); assertTrue(page.getStep() == 5); assertTrue(page.getOffset() == 0); page.step(); assertTrue(page.getOffset() == 5); SymbolTable symbols = page.toSymbolTable(); assertNotNull(symbols); assertTrue(StringUtil.isNotBlank(symbols.getString(NAME + ".start"))); assertTrue(StringUtil.isNotBlank(symbols.getString(NAME + ".size"))); assertTrue(StringUtil.isNotBlank(symbols.getString(NAME + ".end"))); assertTrue(StringUtil.isBlank(symbols.getString(NAME + ".pickle"))); } |
Pagination { public String getName() { return name; } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); } | @Test public void blankName() { Pagination page = new Pagination("", 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); page = new Pagination(" ", 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); page = new Pagination(null, 0, 5); assertEquals(Pagination.DEFAULT_NAME, page.getName()); } |
Token { public static String unquote(String text) { if (text == null) { return null; } final int len = text.length(); if (len < 2 || text.charAt(0) != '"' || text.charAt(len - 1) != '"') { return text; } text = text.substring(1, len - 1); return unescape(text); } static boolean isSeparator(final char ch); static boolean isValid(final String token); static String unescape(final String text); static String unquote(String text); } | @Test public void test014() { unquote("abc", "\"abc\""); }
@Test public void test015() { unquote("\"abc", "\"abc"); }
@Test public void test016() { unquote("abc\"", "abc\""); }
@Test public void test017() { unquote("abc", "\"ab\\c\""); }
@Test public void test018() { unquote("ab\\c", "\"ab\\\\c\""); }
@Test public void test011() { unquote(null, null); }
@Test public void test012() { unquote("", ""); }
@Test public void test013() { unquote("abc", "abc"); } |
Pagination { @Override public String toString() { StringBuilder b = new StringBuilder("Pagination: '"); b.append(getName()); b.append("' start:").append(getStart()); b.append(" step:").append(getStep()); return b.toString(); } Pagination(long step); Pagination(long start, long step); Pagination(String name, long step); Pagination(String name, long start, long step); long getOffset(); synchronized void setOffset(long offset); String getName(); long getStep(); long getStart(); long getEnd(); synchronized void step(); synchronized void reset(); @Override String toString(); @SuppressWarnings("unchecked") synchronized SymbolTable toSymbolTable(); } | @Test public void toStringTest() { final String expected = "Pagination: 'offset' start:0 step:5"; final String NAME = "offset"; Pagination page = new Pagination(NAME, 0, 5); assertEquals(expected, page.toString()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.