I am writing a service(Spring Integration + JavaMail API) that automatically replies to a received message and I am having problems with including the previous message body.
How can I handle it correctly? I'd like to keep the same formatting, the one that Gmail/Thunderbird uses. I included code snippets showing how I've done it, but is there perhaps some other solution I could use? Some library, perhaps? Regular expressions? I sweeped through stackoverflow questions, but answers telling me that I have to handle it on my own aren't exactly helpful.
I'm open to suggestions. Thanks in advance!
On Gmail it looks like this:
Thunderbird:
fun prepareReplyFor(mimeMessage: MimeMessage): MimeMessage
{
val response = mimeMessage.reply(SHOULD_REPLY_TO_ALL) as MimeMessage
val mailFormatter = MailFormatter()
val botText = MimeBodyPart()
botText.setContent("This message was generated.\n", "text/plain")
val previousCorrespondence = MimeBodyPart()
previousCorrespondence.setContent(mailFormatter.formatPrevious(mimeMessage), "text/plain")
val responseBody = MimeMultipart()
responseBody.addBodyPart(botText)
responseBody.addBodyPart(previousCorrespondence)
response.setContent(responseBody)
return response
}
MailFormatter:
const val CORRESPONDENCE_FORMAT_REGEX = "(?m)^"
const val FIRST_BODY_PART = 0
class MailFormatter
{
fun formatPrevious(mimeMessage: MimeMessage): String
{
val previousMessage = mimeMessage.content
var formattedQuote = "In reply to:\n\n"
if (previousMessage is String)
{
formattedQuote += previousMessage.replace(CORRESPONDENCE_FORMAT_REGEX.toRegex(), "> ")
}
else if (previousMessage is MimeMultipart)
{
formattedQuote += (previousMessage.getBodyPart(FIRST_BODY_PART).content as String).replace(CORRESPONDENCE_FORMAT_REGEX.toRegex(), "> ")
}
return formattedQuote
}
}
Related
I am using the below code to get originatingAddress (the sender's number).
import android.provider.Telephony.Sms.Intents.getMessagesFromIntent
fun getFullMessage(messageParts: Array<SmsMessage>): CompleteSmsMessage {
messageParts = getFullMessage(getMessagesFromIntent(intent))
messageParts.last().also { part ->
return CompleteSmsMessage(
originatingAddress = part.originatingAddress,
body = messageParts
.map { it.messageBody }
.reduce { acc, body -> acc + body }
)
}
}
Since I have multiple SIM slots on my phone, I'd like to get the receiver's number as well. I couldn't find any relevant document here: https://developer.android.com/reference/android/telephony/SmsMessage#getDisplayOriginatingAddress()
Is it possible to get the receiver's number? How?
The incoming intent contains subscription variable, this is the SIM slot:
val slotId = intent.getIntExtra("subscription", -1)
I'm using a screenshot library (in Github) and it is has been written in Kotlin(I don't know Kotlin very well).
<https://github.com/bolteu/screenshotty>
I don't know how to translate to Java a part of code.
in the read me file :
val screenshotResult = screenshotManager.makeScreenshot()
val subscription = screenshotResult.observe(
onSuccess = { processScreenshot(it) },
onError = { onMakeScreenshotFailed(it) }
)
It says that you can get a screenshot object from "it"?
how can I do that?
please help me...
and how can I translate this code to Java :
fun show(screenshot: Screenshot) {
val bitmap = when (screenshot) {
is ScreenshotBitmap -> screenshot.bitmap
}
screenshotPreview.setImageBitmap(bitmap)
}
I'm USING GATLING AND trying to use in java's library "Base64" in scala for sending encode uder:password in header ("authorization") request, with dynamic values:
I'm trying to do as follow :
val register = {
exec(request.asJSON
.check(status.is(200))
.check(jsonPath("$..user").saveAs("user"))
.check(jsonPath("$..password").saveAs("password"))
).pause(1)
}
val myvalue: HttpRequestBuilder = Utils.createPostFormParamsRequest(
"myvalue",
login,
Map("value"-> ("Basic " + Base64.getEncoder.encodeToString((("${user}").getBytes() + ":" + ("${password}").getBytes()).getBytes("utf-8")))),
Map())
I'd tried also Base64.getEncoder.encodeToString(("${uesr}" + ":" + "${password}").getBytes("utf-8"))))
But it seems like the Base64 take the String "${user}" and not the actual value, so the encryption does not work properly.
I'd tried to :
val helper = {
exec { session =>
val user : String= (session("user").as[String])
val password : String= (session("password").as[String])
val temp = "Basic " + Base64.getEncoder.encodeToString((user + ":" + password).getBytes("utf-8"))
val temp2: HttpRequestBuilder = Utils.createPostFormParamsRequest(
"bla",
login,
Map("value"-> temp),
Map())
val assert = {
exec(helper.asJSON
.check(status.is(200))
.check(header("answer").saveAs("answer"))
).pause(1)
}
session
}
And here the encryption works properly, but the "exec" do not.
There is a way to save the values in run time without part of the exec?
I don't know Gatling that well, but I think this should work. It's not the prettiest but without seeing the full code and how it's used it's a bit difficult to come up with something that looks good:
var token: String = null
val registerAssert = exec(...)
def finalToken = {
Utils.createPostFormParamsRequest(
"Final token",
Constants.LOGIN,
Map("Authorization"-> token),
Map())
}
def saveToken(s: Session) = {
token = "Basic " + Base64.getEncoder.encodeToString((s("uuid").as[String].getBytes() + ":" + s("secret").as[String].getBytes()).getBytes("utf-8")
s
}
// now you're actually executing the above
scenario(...)
.exec(registerAssert)
.exec(saveToken(_))
.exec(finalToken) // I'm assuming finalToken is executable
The intention of this is to first save the token value in a class variable, and then only construct the finalToken request (which uses that token) afterwards. Hence the def, and when it's called the token value will have been set.
I am working on a script where I need to create the release notes using JIRA REST API in HTML format for any project.The below four field should come in that release notes.
Issue Key Module Summary Release Note
I am trying the below code but it is giving me only the issue Key field but need all other fields as well and in html file.Could you please suggest me on this?
Issue:1
Initially it was giving me the output in below format:
NTTB-2141
NTTB-2144
NTTB-2140
But now it is giving me the output json fromat way.
Code which I am trying from the groovy console:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
import groovyx.net.http.RESTClient
final String USAGE =
"Usage: -Djira.username=xxx -Djira.password=xxx -Djira.fixVersion=1.0"
String jiraUsername = 'ABCDEF'
String jiraPassword = '********'
String jiraFixVersion = '3.8.101'
println "Getting issues..."
if (!jiraUsername?.trim()) {
fail("Empty property: jira.username " + USAGE)
}
if (!jiraPassword?.trim()) {
fail("Empty property: jira.password " + USAGE)
}
if (!jiraFixVersion?.trim()) {
fail("Empty property: jira.fixVersion " + USAGE)
}
final String JIRA_SEARCH_URL = "https://jira.test.com/rest/api/latest/"
// see JIRA docs about search:
// https://docs.atlassian.com/jira/REST/latest/#idp1389824
String JQL = "project = NCCB"
JQL += " AND issuetype in standardIssueTypes()"
JQL += " AND status in (Resolved, Closed)"
JQL += " AND fixVersion = \"${jiraFixVersion}\""
def jira = new RESTClient(JIRA_SEARCH_URL)
def query = [:]
query['os_username'] = jiraUsername
query['os_password'] = jiraPassword
query['jql'] = JQL
query['startAt'] = 0
query['maxResults'] = 1000
try {
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
assert (resp.data instanceof net.sf.json.JSON)
resp.data.issues.each { issue ->
println issue.key
}
println "Total issues: " + resp.data.total
} catch (groovyx.net.http.HttpResponseException e) {
if (e.response.status == 400) {
// HTTP 400: Bad Request, JIRA JQL error
fail("JIRA query failed: ${e.response.data}", e)
} else {
fail("Failure HTTP status ${e.response.status}", e)
}
}
I suspect the code is right, except for that assertion:
assert (resp.data instanceof net.sf.json.JSON)
I get a groovy.json.internal.LazyMap (maybe you have changed versions of Groovy or Jira or something).
As a result, the assertion fails and Groovy tries to be helpful by giving you a comparison... but it shows you the toString() of the result, which is a huge mess of maps.
If you remove that assertion, it works for me, and I suspect it will work for you too.
Edit: huh... you cannot literally take "all" data and print to html. You will have to select the properties you need, and those depend on your Jira configuration. Here is an example with only 2 properties that should be universal:
def resp = jira.get(path: "search",
contentType: "application/json",
query: query)
assert resp.status == 200
def output = new File('issues.html')
output << "<html><body><ul>"
resp.data.issues.each { issue ->
def url = "https://yourjirainstance/browse/${issue.key}"
output << "<li>${issue.key}: ${issue.fields.summary}</li>"
}
output << "</ul></body></html>"
println "Exported ${resp.data.total} issues to ${output.name}"
See here details about what the service will give you.
If you just want an HTML dump, maybe the REST API is not what you want: you can also ask Jira to export results of JQL as a printable output (that will actually be html).
I have a WebSocket in my Play application and I want to write a test for it, but I couldn't find any example on how to write such a test. I found a discussion in the play-framework Google group but there has been no activity recently.
So, are there any ideas on how to test WebSocket's in a Java test?
You can retrieve underlying Iteratee,Enumerator and test them directly. This way you don't need to use a browser. You need akka-testkit though, to cope with asynchronous nature of iteratees.
A Scala example:
object WebSocket extends Controller {
def websocket = WebSocket.async[JsValue] { request =>
Future.successful(Iteratee.ignore[JsValue] -> Enumerator.apply[JsValue](Json.obj("type" -> "error")))
}
}
class WebSocketSpec extends PlaySpecification {
"WebSocket" should {
"respond with error packet" in new WithApplication {
val request = FakeRequest()
var message: JsValue = null
val iteratee = Iteratee.foreach[JsValue](chunk => message = chunk)(Akka.system.dispatcher)
Controller.websocket().f(request)(Enumerator.empty[JsValue],iteratee)
TestKit.awaitCond(message == Json.obj("type" -> "error"), 1 second)
}
}
}
I test WebSockets code using Firefox:
https://github.com/schleichardt/stackoverflow-answers/commit/13d5876791ef409e092e4a097f54247d851e17dc#L8R14
For Java it works similar replacing 'HTMLUNIT' with 'FIREFOX': http://www.playframework.com/documentation/2.1.x/JavaFunctionalTest
Chrome provides a plugin to test websocket service.
Edit
So using the plugin (as shown in picture below) you can provide websocket url and the request data and send message to service. And message log shows the message sent from client and also service response.
Assume that you have a websocket library that returns the Future[Itearatee[JsValue, Unit], Enumerator[JsValue]] your controller uses
trait WSLib {
def connect: Future[Itearatee[JsValue, Unit], Enumerator[JsValue]]
}
And you wanna test this library.
Here is a context you can use:
trait WebSocketContext extends WithApplication {
val aSecond = FiniteDuration(1, TimeUnit.SECONDS)
case class Incoming(iteratee: Iteratee[JsValue, Unit]) {
def feed(message: JsValue) = {
iteratee.feed(Input.El(message))
}
def end(wait: Long = 100) = {
Thread.sleep(wait) //wait until all previous fed messages are handled
iteratee.feed(Input.EOF)
}
}
case class OutGoing(enum: Enumerator[JsValue]) {
val messages = enum(Iteratee.fold(List[JsValue]()) {
(l, jsValue) => jsValue :: l
}).flatMap(_.run)
def get: List[JsValue] = {
Await.result(messages, aSecond)
}
}
def wrapConnection(connection: => Future[Iteratee[JsValue, Unit], Enumerator[JsValue]]): (Incoming, OutGoing) = {
val (iteratee, enumerator) = Await.result(conn, aSecond)
(Incoming(iteratee), OutGoing(enumerator))
}
}
Then your tests can be written as
"return all subscribers when asked for info" in new WebSocketContext {
val (incoming, outgoing) = wrapConnection(myWSLib.connect)
incoming.feed(JsObject("message" => "hello"))
incoming.end() //this closes the connection
val responseMessages = outgoing.get //you only call this "get" after the connection is closed
responseMessages.size must equalTo(1)
responseMessages must contain(JsObject("reply" => "Hey"))
}
Incoming represent the messages coming from the client side, while the outgoing represents the messages sent from the server. To write test, you first feed in the incoming messages from incoming and then close the connection by calling incoming.end, then you get the complete list of outgoing messages from the outgoing.get method.