android.app.Application cannot be cast to com.example.skillit.data.InventoryApplication(DATA BASE) - database

2022-12-11 02:50:28.862 24393-24393/com.example.skillit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.skillit, PID: 24393
java.lang.ClassCastException: android.app.Application cannot be cast to com.example.skillit.data.InventoryApplication
at com.example.skillit.ProfileActivity$viewModel$2.invoke(ProfileActivity.kt:22)
at com.example.skillit.ProfileActivity$viewModel$2.invoke(ProfileActivity.kt:21)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:47)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:35)
at com.example.skillit.ProfileActivity.getViewModel(ProfileActivity.kt:21)
at com.example.skillit.ProfileActivity.onCreate$lambda$3(ProfileActivity.kt:51)
at com.example.skillit.ProfileActivity.$r8$lambda$733-BBVTFBdHTXlcl6xFIzJMP3c(Unknown Source:0)
at com.example.skillit.ProfileActivity$$ExternalSyntheticLambda3.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7881)
at android.widget.TextView.performClick(TextView.java:16201)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
at android.view.View.performClickInternal(View.java:7858)
at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
at android.view.View$PerformClick.run(View.java:30863)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8741)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
THIS IS THE ProfileActivity.kt code:
package com.example.skillit
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Button
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.activityViewModels
import com.example.skillit.data.InventoryApplication
import com.example.skillit.databinding.FragmentItemDetailBinding
import com.example.skillit.databinding.ProfileActivityBinding
class ProfileActivity : AppCompatActivity() {
//private var _binding: ProfileActivityBinding? = null
//private val binding get() = _binding!!
private val viewModel: InventoryViewModel by viewModels {
InventoryViewModelFactory((application as InventoryApplication).database.itemDao())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.supportActionBar?.hide()
//_binding = ProfileActivityBinding.inflate(LayoutInflater.from(this))
//setContentView(binding.root)
setContentView(R.layout.profile_activity)
val explore_button = findViewById(R.id.explore_button) as CardView
val profile_button = findViewById(R.id.profile_button) as CardView
val home_button = findViewById(R.id.home_button) as CardView
val upload_button = findViewById<Button>(R.id.upload)
home_button.setOnClickListener{
intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
}
explore_button.setOnClickListener{
intent = Intent(this, ExploreActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
}
profile_button.setOnClickListener{
intent = Intent(this, ProfileActivity::class.java)
startActivity(intent)
}
upload_button.setOnClickListener{
viewModel.addNewItem("name", "link")
}
}
}
THIS IS THE InventoryAplication.kt code:
package com.example.skillit.data
import android.app.Application
class InventoryApplication : Application() {
val database: ItemRoomDatabase by lazy { ItemRoomDatabase.getDatabase(this) }
}
THIS IS THE ItemRoomDatabase.kt code:
package com.example.skillit.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
#Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class ItemRoomDatabase : RoomDatabase() {
abstract fun itemDao(): ItemDao
companion object {
#Volatile
private var INSTANCE: ItemRoomDatabase? = null
fun getDatabase(context: Context): ItemRoomDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ItemRoomDatabase::class.java,
"item_database"
)
// Wipes and rebuilds instead of migrating if no Migration object.
// Migration is not part of this codelab.
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
// return instance
instance
}
}
}
}
I tried to upload data to a database when you press the upload_button in the ProfileActivity.kt file but when you do, in the "Logcat" tab it keeps showing me the error mentioned above, I think the problem is with the ItemRoomDatabase but I cant figure out what doesn't work .

Related

Can't execute a transaction block while working with a database. Kotlin, Exposed

I am trying to send transactions to the Postgre database (the table exists) using the Exposed framework for Kotlin, but an error occurs that does not allow me to do this. The error appears on the line SchemaUtils.create(tableTest)
Source code:
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
fun main(args: Array<String>) {
val db = Database.connect("jdbc:postgresql://localhost:5432/testBase", driver = "org.postgresql.Driver", user = "user", password = "123")
println("Database name: ${db.name}")
transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(tableTest)
println("People: ${tableTest.selectAll()}")
}
}
object tableTest: Table() {
val id = integer("id")
val name = text("name")
val surname = text("surname")
val height = integer("height")
val phone = text("phone")
override val primaryKey = PrimaryKey(id)
}
The error:
Exception in thread "main" java.lang.ExceptionInInitializerError
at MainKt$main$1.invoke(main.kt:12)
at MainKt$main$1.invoke(main.kt)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt$inTopLevelTransaction$1.invoke(ThreadLocalTransactionManager.kt:170)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt$inTopLevelTransaction$2.invoke(ThreadLocalTransactionManager.kt:211)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.keepAndRestoreTransactionRefAfterRun(ThreadLocalTransactionManager.kt:219)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.inTopLevelTransaction(ThreadLocalTransactionManager.kt:210)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt$transaction$1.invoke(ThreadLocalTransactionManager.kt:148)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.keepAndRestoreTransactionRefAfterRun(ThreadLocalTransactionManager.kt:219)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.transaction(ThreadLocalTransactionManager.kt:120)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.transaction(ThreadLocalTransactionManager.kt:118)
at org.jetbrains.exposed.sql.transactions.ThreadLocalTransactionManagerKt.transaction$default(ThreadLocalTransactionManager.kt:117)
at MainKt.main(main.kt:10)
Caused by: java.lang.IllegalStateException: javaClass.`package` must not be null
at org.jetbrains.exposed.sql.Table.<init>(Table.kt:306)
at org.jetbrains.exposed.sql.Table.<init>(Table.kt:303)
at tableTest.<init>(main.kt:30)
at tableTest.<clinit>(main.kt:30)
... 12 more
build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.4.0"
application
}
group = "me.amd"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
jcenter()
}
dependencies {
testImplementation(kotlin("test-junit"))
implementation("org.jetbrains.exposed", "exposed-core", "0.26.2")
implementation("org.jetbrains.exposed", "exposed-dao", "0.26.2")
implementation("org.jetbrains.exposed", "exposed-jdbc", "0.26.2")
implementation("org.postgresql:postgresql:42.2.16")
implementation("org.slf4j", "slf4j-api", "1.7.25")
implementation("org.slf4j", "slf4j-simple", "1.7.25")
implementation("org.xerial:sqlite-jdbc:3.30.1")
}
tasks.withType<KotlinCompile>() {
kotlinOptions.jvmTarget = "1.8"
}
application {
mainClassName = "MainKt"
}
Tried doing like this:
transaction {
addLogger(StdOutSqlLogger)
val schema = Schema("tableTest", authorization = "postgres", password = "123456")
SchemaUtils.setSchema(schema)
println("People: ${tableTest.selectAll()}")
}
but the error has moved to the line println("People: ${tableTest.selectAll()}")
I tried to send queries to SQLite — everything is the same
How to fix this error and still send a request to the database? I hope for your help!
Add a package statement above your import statements. Furthermore, add your main method in a class.

Backpressure in connected flink streams

I am experimenting with how to propagate back-pressure correctly when I have ConnectedStreams as part of my computation graph. The problem is: I have two sources and one ingests data faster than the other, think we want to replay some data and one source has rare events that we use to enrich the other source. These two sources are then connected in a stream that expects them to be at least somewhat synchronized, merges them together somehow (making tuple, enriching, ...) and returns a result.
With single input streams its fairly easy to implement backpressure, you simply have to spend long time in the processElement function. With connectedstreams my initial idea was to have some logic in each of the processFunctions that waits for the other stream to catch up. For example I could have a buffer thats time-span limited (large enough span to fit a watermark) and the function would not accept events that would make this span pass a threshold. For example:
leftLock.aquire { nonEmptySignal =>
while (queueSpan() > capacity.toMillis && lastTs() < ctx.timestamp()) {
println("WAITING")
nonEmptySignal.await()
}
queueOp { queue =>
println(s"Left Event $value recieved ${Thread.currentThread()}")
queue.add(Left(value))
}
ctx.timerService().registerEventTimeTimer(value.ts)
}
Full code of my example is below (its written with two locks assuming access from two different threads, which is not the case - i think):
import java.util.concurrent.atomic.{AtomicBoolean, AtomicLong}
import java.util.concurrent.locks.{Condition, ReentrantLock}
import scala.collection.JavaConverters._
import com.google.common.collect.MinMaxPriorityQueue
import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
import org.apache.flink.api.common.typeinfo.{TypeHint, TypeInformation}
import org.apache.flink.api.java.utils.ParameterTool
import org.apache.flink.api.scala._
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.environment.LocalStreamEnvironment
import org.apache.flink.streaming.api.functions.co.CoProcessFunction
import org.apache.flink.streaming.api.functions.source.{RichSourceFunction, SourceFunction}
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.streaming.api.watermark.Watermark
import org.apache.flink.util.Collector
import scala.collection.mutable
import scala.concurrent.duration._
trait Timestamped {
val ts: Long
}
case class StateObject(ts: Long, state: String) extends Timestamped
case class DataObject(ts: Long, data: String) extends Timestamped
case class StatefulDataObject(ts: Long, state: Option[String], data: String) extends Timestamped
class DataSource[A](factory: Long => A, rate: Int, speedUpFactor: Long = 0) extends RichSourceFunction[A] {
private val max = new AtomicLong()
private val isRunning = new AtomicBoolean(false)
private val speedUp = new AtomicLong(0)
private val WatermarkDelay = 5 seconds
override def cancel(): Unit = {
isRunning.set(false)
}
override def run(ctx: SourceFunction.SourceContext[A]): Unit = {
isRunning.set(true)
while (isRunning.get()) {
val time = System.currentTimeMillis() + speedUp.addAndGet(speedUpFactor)
val event = factory(time)
ctx.collectWithTimestamp(event, time)
println(s"Event $event sourced $speedUpFactor")
val watermark = time - WatermarkDelay.toMillis
if (max.get() < watermark) {
ctx.emitWatermark(new Watermark(time - WatermarkDelay.toMillis))
max.set(watermark)
}
Thread.sleep(rate)
}
}
}
class ConditionalOperator {
private val lock = new ReentrantLock()
private val signal: Condition = lock.newCondition()
def aquire[B](func: Condition => B): B = {
lock.lock()
try {
func(signal)
} finally {
lock.unlock()
}
}
}
class BlockingCoProcessFunction(capacity: FiniteDuration = 20 seconds)
extends CoProcessFunction[StateObject, DataObject, StatefulDataObject] {
private type MergedType = Either[StateObject, DataObject]
private lazy val leftLock = new ConditionalOperator()
private lazy val rightLock = new ConditionalOperator()
private var queueState: ValueState[MinMaxPriorityQueue[MergedType]] = _
private var dataState: ValueState[StateObject] = _
override def open(parameters: Configuration): Unit = {
super.open(parameters)
queueState = getRuntimeContext.getState(new ValueStateDescriptor[MinMaxPriorityQueue[MergedType]](
"event-queue",
TypeInformation.of(new TypeHint[MinMaxPriorityQueue[MergedType]]() {})
))
dataState = getRuntimeContext.getState(new ValueStateDescriptor[StateObject](
"event-state",
TypeInformation.of(new TypeHint[StateObject]() {})
))
}
override def processElement1(value: StateObject,
ctx: CoProcessFunction[StateObject, DataObject, StatefulDataObject]#Context,
out: Collector[StatefulDataObject]): Unit = {
leftLock.aquire { nonEmptySignal =>
while (queueSpan() > capacity.toMillis && lastTs() < ctx.timestamp()) {
println("WAITING")
nonEmptySignal.await()
}
queueOp { queue =>
println(s"Left Event $value recieved ${Thread.currentThread()}")
queue.add(Left(value))
}
ctx.timerService().registerEventTimeTimer(value.ts)
}
}
override def processElement2(value: DataObject,
ctx: CoProcessFunction[StateObject, DataObject, StatefulDataObject]#Context,
out: Collector[StatefulDataObject]): Unit = {
rightLock.aquire { nonEmptySignal =>
while (queueSpan() > capacity.toMillis && lastTs() < ctx.timestamp()) {
println("WAITING")
nonEmptySignal.await()
}
queueOp { queue =>
println(s"Right Event $value recieved ${Thread.currentThread()}")
queue.add(Right(value))
}
ctx.timerService().registerEventTimeTimer(value.ts)
}
}
override def onTimer(timestamp: Long,
ctx: CoProcessFunction[StateObject, DataObject, StatefulDataObject]#OnTimerContext,
out: Collector[StatefulDataObject]): Unit = {
println(s"Watermarked $timestamp")
leftLock.aquire { leftSignal =>
rightLock.aquire { rightSignal =>
queueOp { queue =>
while (Option(queue.peekFirst()).exists(x => timestampOf(x) <= timestamp)) {
queue.poll() match {
case Left(state) =>
dataState.update(state)
leftSignal.signal()
case Right(event) =>
println(s"Event $event emitted ${Thread.currentThread()}")
out.collect(
StatefulDataObject(
event.ts,
Option(dataState.value()).map(_.state),
event.data
)
)
rightSignal.signal()
}
}
}
}
}
}
private def queueOp[B](func: MinMaxPriorityQueue[MergedType] => B): B = queueState.synchronized {
val queue = Option(queueState.value()).
getOrElse(
MinMaxPriorityQueue.
orderedBy(Ordering.by((x: MergedType) => timestampOf(x))).create[MergedType]()
)
val result = func(queue)
queueState.update(queue)
result
}
private def timestampOf(data: MergedType): Long = data match {
case Left(y) =>
y.ts
case Right(y) =>
y.ts
}
private def queueSpan(): Long = {
queueOp { queue =>
val firstTs = Option(queue.peekFirst()).map(timestampOf).getOrElse(Long.MaxValue)
val lastTs = Option(queue.peekLast()).map(timestampOf).getOrElse(Long.MinValue)
println(s"Span: $firstTs - $lastTs = ${lastTs - firstTs}")
lastTs - firstTs
}
}
private def lastTs(): Long = {
queueOp { queue =>
Option(queue.peekLast()).map(timestampOf).getOrElse(Long.MinValue)
}
}
}
object BackpressureTest {
var data = new mutable.ArrayBuffer[DataObject]()
def main(args: Array[String]): Unit = {
val streamConfig = new Configuration()
val env = new StreamExecutionEnvironment(new LocalStreamEnvironment(streamConfig))
env.getConfig.disableSysoutLogging()
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
env.setParallelism(1)
val stateSource = env.addSource(new DataSource(ts => StateObject(ts, ts.toString), 1000))
val dataSource = env.addSource(new DataSource(ts => DataObject(ts, ts.toString), 100, 100))
stateSource.
connect(dataSource).
keyBy(_ => "", _ => "").
process(new BlockingCoProcessFunction()).
print()
env.execute()
}
}
The problem with connected streams is it seems you cant simply block in one of the processFunctions when its stream is too far ahead, since that blocks the other processFunction aswell. On the other hand if i simply accepted all events in this job eventually the process function would run out of memory. Since it would buffer the whole stream that is ahead.
So my question is: Is it possible to propagate backpressure into each of the streams in ConnectedStreams separately and if so, how? Or alternatively, is there any other nice way to deal with this issue? Possibly all the sources communicating somehow to keep them mostly at the same event-time?
From my reading of the code in StreamTwoInputProcessor, it looks to me like the processInput() method is responsible for implementing the policy in question. Perhaps one could implement a variant that reads from whichever stream has the lower watermark, so long as it has unread input. Not sure what impact that would have overall, however.

Akka http-client can't consume all stream of data from server

Im trying to write a simple akka stream rest endpoint and client for consuming this stream. But then i try to run server and client, client is able to consume only part of stream. I can't see any exception during execution.
Here are my server and client:
import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.common.{EntityStreamingSupport, JsonEntityStreamingSupport}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.stream.{ActorAttributes, ActorMaterializer, Attributes, Supervision}
import akka.stream.scaladsl.{Flow, Source}
import akka.util.ByteString
import spray.json.DefaultJsonProtocol
import scala.io.StdIn
import scala.util.Random
object WebServer {
object Model {
case class Person(id: Int = Random.nextInt(), fName: String = Random.nextString(10), sName: String = Random.nextString(10))
}
object JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
implicit val personFormat = jsonFormat(Model.Person.apply, "id", "firstName", "secondaryName")
}
def main(args: Array[String]) {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val start = ByteString.empty
val sep = ByteString("\n")
val end = ByteString.empty
import JsonProtocol._
implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()
.withFramingRenderer(Flow[ByteString].intersperse(start, sep, end))
.withParallelMarshalling(parallelism = 8, unordered = false)
val decider: Supervision.Decider = {
case ex: Throwable => {
println("Exception occurs")
ex.printStackTrace()
Supervision.Resume
}
}
val persons: Source[Model.Person, NotUsed] = Source.fromIterator(
() => (0 to 1000000).map(id => Model.Person(id = id)).iterator
)
.withAttributes(ActorAttributes.supervisionStrategy(decider))
.map(p => { println(p); p })
val route =
path("persons") {
get {
complete(persons)
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine()
bindingFuture
.flatMap(_.unbind())
.onComplete(_ => {
println("Stopping http server ...")
system.terminate()
})
}
}
and client:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, Uri}
import akka.stream.{ActorAttributes, ActorMaterializer, Supervision}
import scala.util.{Failure, Success}
object WebClient {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val request = HttpRequest(uri = Uri("http://localhost:8080/persons"))
val response = Http().singleRequest(request)
val attributes = ActorAttributes.withSupervisionStrategy {
case ex: Throwable => {
println("Exception occurs")
ex.printStackTrace
Supervision.Resume
}
}
response.map(r => {
r.entity.dataBytes.withAttributes(attributes)
}).onComplete {
case Success(db) => db.map(bs => bs.utf8String).runForeach(println)
case Failure(ex) => ex.printStackTrace()
}
}
}
it works for 100, 1000, 10 000 persons but does not work for > 100 000'.
It looks like there is some limit for stream but i can't find it
Last record has been printed by server on my local machine is (with number 79101):
Person(79101,ⰷ瑐劲죗醂竜泲늎制䠸,䮳硝沢并⎗ᝨᫌꊭᐽ酡)
Last record on client is(with number 79048):
{"id":79048,"firstName":"췁頔䚐龫暀࡙頨捜昗㢵","secondaryName":"⏉ݾ袈庩컆◁ꄹ葪䑥Ϻ"}
Maybe somebody know why it happens?
I found a solution. I have to explicitly add r.entity.withoutSizeLimit() on client and after that all works as expected

how to Add attachment in ICS file

I tried to add attachment in ics file but it not showing in outlook when open it. I am trying to add attachment like when we send meeting request and add attachment in that from outlook, that attachment can view from calendar as well. This is my ics file :
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//appform.com//NONSGML kigkonsult.se iCalcreator 2.18//
METHOD:PUBLISH
X-WR-TIMEZONE:UTC
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
UID:20160719T144014-694839744#appform.com
DTSTAMP:20160719T124014Z
ATTACH;FMTTYPE="application/msword; charset=binary";FILENAME=1468827330fCrj
O.doc:/var/www/html/basearch.appform.com/application/../public/uploads/146
8827330fCrjO.doc
ATTENDEE;RSVP=TRUE;SENT-BY="MAILTO:sajal#mailinator.com";CN=satyendra#hirest
orm.com;DIR="/var/www/html/app/application/../public/uplo
ads/1468827330fCrjO.doc";LANGUAGE=us-EN;X-AGENDA=Interview;X-LENGTH=30 min
:MAILTO:satyendra#mailinator.com
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614e321f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614cdn.com/146297361
8PwEwE.jpeg\n
DTSTART:20160720T090000Z
DTEND:20160720T093000Z
LOCATION:1 2 Elmshorn Schleswig-Holstein Germany
SEQUENCE:0
SUMMARY:New Interview Confirmed: Dean Nestle Jones G for test
BEGIN:VALARM
ACTION:PROCEDURE
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614ce048a5e321d7d0f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614ce048a5e32cdn.com/146297361
8PwEwE.jpeg\n
TRIGGER:-PT0H15M0S
END:VALARM
END:VEVENT
END:VCALENDAR
Your iCalendar file contains a reference to :
/var/www/html/basearch.appform.com/application/../public/uploads/1468827330fCrjO.doc
This would obviously be something on your machine. You're not embedding any file, you're just pasting a local path. Unless you have Outlook running on linux there's no way it can find that path.
I tried to do it in a simple java
import java.io.IOException;
import java.net.URI;
import java.text.ParseException;
import java.util.HashMap;
import javax.activation.DataHandler;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import com.tba.readProps.Constants;
import com.tba.readProps.ReadProps;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.RandomUidGenerator;
import net.fortuna.ical4j.util.UidGenerator;
public class EmailWithCalendar{
/**
* #param emailAddr
* #param subject
* #param message
*/
public static void sendHtmlEmail(String emailAddr, String subject, String message){
HashMap propertyValues = null;
String smtpHost = "";
try {
propertyValues = ReadProps.initializeProperties();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
smtpHost = (String) propertyValues.get(Constants.SMTP_HOST);
//ManagerPropertiesBean mgrProps = new ManagerPropertiesBean();
//String smtpHost = mgrProps.getMgrProperty("smtpHost");
try {
// start a session with given properties
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
Session mailSession = Session.getDefaultInstance(props, null);
String fromAddress = null;
fromAddress = (String) propertyValues.get(Constants.FROM_ADDRESS);
if(!"undefined".equals(fromAddress)){
InternetAddress fromAddr = new InternetAddress("test#test.com");
InternetAddress toAddr = new InternetAddress(emailAddr);
MimeMessage myMessage = new MimeMessage(mailSession);
String replyToAddress = null;
replyToAddress = (String) propertyValues.get(Constants.REPLY_ADDRESS);
InternetAddress replyToAddr[] = new InternetAddress[1];
if(!"undefined".equals(replyToAddress))
replyToAddr[0] = new InternetAddress(replyToAddress);
boolean isfromValid = true;
boolean isToValid = true;
boolean emailDomainCheck = true;
MimeBodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(message ,"text/html" );
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
myMessage.setContent(multipart);
if(emailDomainCheck==true)
{
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
myMessage.setReplyTo(replyToAddr);
}
else
{
myMessage.setFrom(fromAddr);
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
if(!"undefined".equals(replyToAddress))
myMessage.setReplyTo(replyToAddr);
}
myMessage.setSentDate(new java.util.Date());
myMessage.setSubject(subject);
messageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(createEvent().toString(), "text/calendar")));// very important
//myMessage.setText(message);
// now send the message!
if(emailDomainCheck==true)
{
if(isfromValid==true && isToValid==true)
{
Transport.send(myMessage);
}
}
else
{
Transport.send(myMessage);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error occurred in ManagerEmailBean.sendHtmlEmail()");
}
}
private static Calendar createEvent() throws ParseException {
// Create the event
String eventName = "Progress Meeting";
//DateTime start = new DateTime(startDate.getTime());
//DateTime end = new DateTime(endDate.getTime());
// Create the date range which is desired.
DateTime start = new DateTime("20100101T070000Z");
DateTime end = new DateTime("20100201T070000Z");;
Period period = new Period(start, end);
VEvent meeting = new VEvent(start, end, eventName);
// add timezone info..
//meeting.getProperties().add(tz.getTimeZoneId());
// generate unique identifier..
UidGenerator ug = new RandomUidGenerator();
Uid uid = ug.generateUid();
meeting.getProperties().add(uid);
// add attendees..
Attendee dev1 = new Attendee(URI.create("mailto:dev1#test.com"));
dev1.getParameters().add(Role.REQ_PARTICIPANT);
dev1.getParameters().add(new Cn("Developer 1"));
meeting.getProperties().add(dev1);
Attendee dev2 = new Attendee(URI.create("mailto:dev2#test.com"));
dev2.getParameters().add(Role.OPT_PARTICIPANT);
dev2.getParameters().add(new Cn("Developer 2"));
meeting.getProperties().add(dev2);
// Create a calendar
net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(Version.VERSION_2_0);
icsCalendar.getProperties().add(CalScale.GREGORIAN);
// Add the event and print
icsCalendar.getComponents().add(meeting);
System.out.println(icsCalendar);
return icsCalendar;
}
public static void main(String[] args) {
sendHtmlEmail("dev.test#gmail.com", "Test", "sjgsfgsf<p>dshdfsdf</p>");
}
}

Sending LDAP request with message ID

Need to send an LDAP search request with message ID set to 0 value (as part of RFC validation testing). Tried the following modified code from apache directory api examples section:
import java.io.IOException;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.exception.LdapNoPermissionException;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
public class ManageLDAPConnection {
private static Dn getSafeSearchBaseDn(String dn) throws LdapInvalidDnException{
Dn searchBaseDn = null;
if (dn != null && !dn.isEmpty()){
searchBaseDn = new Dn(dn);
}else{
searchBaseDn = Dn.ROOT_DSE;
}
return searchBaseDn;
}
public static void main (String[] args) {
int messageId = 0;
int port = 389;
String username = "<Admin CN>";
String password = "<Password>";
String hostname = "<IP>";
SearchCursor searchResult = null;
String dn = "<DN>";
String filterExpr = "(objectclass=*)";
org.apache.directory.api.ldap.model.message.SearchScope searchScopeValue = org.apache.directory.api.ldap.model.message.SearchScope.OBJECT;
LdapConnection connection = new LdapNetworkConnection(hostname, port);
try {
connection.bind(username, password);
System.out.println("Connected successfully");
} catch (LdapException e) {
System.out.println("Unable to bind");
}
try {
SearchRequest searchRequest = new SearchRequestImpl();
System.out.println(searchRequest.getMessageId());
searchRequest.setMessageId(0);
System.out.println(searchRequest.getMessageId());
searchRequest.setBase(getSafeSearchBaseDn(dn));
searchRequest.setFilter(filterExpr);
searchRequest.setScope(searchScopeValue);
searchResult = connection.search(searchRequest);
} catch (LdapNoPermissionException e){
System.out.println("No permission exception");
} catch (LdapException e){
System.out.println("LDAP Exception: " + e.getMessage());
}
}
}
The above code is able to send the request, but the message ID is still sent as non zero,
even though the following has been done:
searchRequest.setMessageId(0);
You're clearly going to have to use a different library, or modify this one, or go to a lower level. It isn't at all surprising that this library prevents you from shooting yourself in the foot.
Had some solution in python's pyasn1-modules. The following seems to work well:
from pyasn1.type import univ, namedval, namedtype, tag
from pyasn1.codec.ber import encoder
import socket
from pyasn1_modules.rfc2251 import *
ldap_bind_request = BindRequest()
ldap_bind_request.setComponentByName('version', 3)
ldap_bind_request.setComponentByName('name', 'cn=admin,o=org')
ldap_auth = AuthenticationChoice()
ldap_auth.setComponentByName('simple', 'mypwd')
ldap_bind_request.setComponentByName('authentication', ldap_auth)
ldap_message = LDAPMessage()
ldap_message.setComponentByName('messageID', 0)
ldap_message.setComponentByName('protocolOp', ldap_bind_request)
print(ldap_bind_request.prettyPrint())
print(dir(ldap_bind_request))
encoded_request = encoder.encode(ldap_message)
print(encoded_request)
asock = socket.socket()
asock.connect(('127.0.0.1', 389))
asock.send(encoded_request)
There is something named JAVA ASN.1 Compiler (JAC). Trying to see if they provide something similar, with less of object oriented complexity which is common in java :)

Resources