Casting java.sql.Connection to oracle.jdbc.OracleConnection results in compilation error - oracle11g

I would like to cast java.sql.Connection to oracle.jdbc.OracleConnection in order to bind data on ARRAY to my query.
When I try the following on scala 2.10, bonecp 0.8.0 and slick 2.0.0:
import com.jolbox.bonecp.ConnectionHandle
import oracle.jdbc.OracleConnection
def failsWithCompilationError() = {
Database.forDataSource(ds).withDynTransaction {
val connection = dynamicSession.conn.asInstanceOf[ConnectionHandle].getInternalConnection
println(connection.unwrap(classOf[OracleConnection]))
// When uncommenting following two lines a compilation error "error while loading AQMessage, class file '.../ojdbc6.jar(oracle/jdbc/aq/AQMessage.class)' is broken" will occur
// val oracleConnection: OracleConnection = connection.unwrap(classOf[OracleConnection])
// println(oracleConnection)
}
}
and uncomment the two lines with assignment to a val of type OracleConnection and printlna compilation failure
[error] error while loading AQMessage, class file '.../ojdbc6.jar(oracle/jdbc/aq/AQMessage.class)' is broken will occur.
I already verified that the ojdbc6.jar should not be corrupted by downloading newer version from Oracle.

It seems that the problem was with the Scala compiler.
As soon as I embedded the functionality that depended on oracle.jdbc.OracleConnection into a plain old Java class, built that into a separate .jar and linked with my Scala code things started to roll.
Here's how I got this to work:
OracleArray.java
package my.application.oracle.collections;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OraclePreparedStatement;
import oracle.sql.ARRAY;
import scala.Long;
import scala.Tuple2;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/*
Wraps usage of Oracle ARRAYs since casting java.sql.Connection to oracle.jdbc.Connection does not compile on Scala.
*/
public class OracleArray {
public static List<Tuple2<Long, Long>> fetchAssetsByIds(List ids, Connection connection) throws SQLException {
OracleConnection oracleConnection = (OracleConnection) connection;
ARRAY oracleArray = oracleConnection.createARRAY("MY_ARRAY_SQL_TYPE", ids.toArray());
String sql = "SELECT a.id, a.value" +
"FROM ASSET a " +
"WHERE a.id IN (SELECT COLUMN_VALUE FROM TABLE(?))";
PreparedStatement statement = oracleConnection.prepareStatement(sql);
try {
OraclePreparedStatement oraclePreparedStatement = (OraclePreparedStatement) statement;
oraclePreparedStatement.setArray(1, oracleArray);
ResultSet resultSet = oraclePreparedStatement.executeQuery();
try {
ArrayList<Tuple2<Long, Long>> resultTuples = new ArrayList<>();
while (resultSet.next()) {
long id = resultSet.getLong(1);
long value = resultSet.getLong(2);
resultTuples.add(new Tuple2(id, value));
}
return resultTuples;
} finally {
resultSet.close();
}
} finally {
statement.close();
}
}
}
DataUser.scala
package my.application
import my.application.oracle.collections.OracleArray
import scala.slick.driver.JdbcDriver.backend.Database
import Database.dynamicSession
import com.jolbox.bonecp.ConnectionHandle
import java.sql.Connection
import collection.JavaConversions._
/*
Uses BoneCP and Slick to connect to database and relays java.sql.Connection to
OracleArray in order to run operations that use Oracle ARRAYs
*/
object DataUser {
def doSomethingWithAssets(ids: Seq[Long]): Unit = {
Database.forDataSource(ds).withDynTransaction {
val connection: Connection = dynamicSession.conn.asInstanceOf[ConnectionHandle].getInternalConnection
val assets: Seq[(Long, Long)] = OracleArray.fetchAssetsByIds(ids, connection)
println(assets)
}
}
}

Not sure if my situation is related, but using the Play framework, this works for me only when logSql=false:
db.withConnection { implicit c =>
val oracleConnection = c.unwrap(classOf[OracleConnection])
}
When I set logSql=true, I get:
com.sun.proxy.$Proxy17 cannot be cast to oracle.jdbc.OracleConnection
java.lang.ClassCastException: com.sun.proxy.$Proxy17 cannot be cast to
oracle.jdbc.OracleConnection
So something about the logSql configuration can actually cause unwrap to fail. No idea why.
I think this may be related to Hikari Connection Pool, but maybe your connection pool configuration is causing a similar problem.

Related

How to pass my viewmodel to a class that does not extend activity

How to pass my viewmodel to a class that does not extend activity
I'm calling my viewmodel like this:
in my EntryAbstract class
where am I going wrong
val FrutasViewModel = ViewModelProvider.NewInstanceFactory().create(FrutasViewModel::class.java)
FrutasViewModel.frutaData.value.forEach { item->
itens.add(ShoppingCart
(id=item.id,photo=item.photo,
name=item.name,quantidade=item.quantidade
,categoria = item.categoria,descricao = item.descricao
,unidade=item.unidade,kilo = item.kilo
))
}
my viewmodel:
package com.example.quitanda.models
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class FrutasViewModel(
private val frutasServices: Services,
):ViewModel() {
private val _frutasData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow<List<ShoppingCart>>(listOf<ShoppingCart>(ShoppingCart()))
val frutaData: StateFlow<List<ShoppingCart>>
get() = _frutasData
fun getFrutas(){
viewModelScope.launch {
try {
val frutas = frutasServices.getFruta()
_frutasData.value = frutas
}catch (e:Exception){
Log.d("Service error",e.toString())
}
}
}
}
My service:
package com.example.quitanda.models
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
interface Services {
#GET("/category/7")
suspend fun getFruta(
//#Query("apikey")
//apikey:String = "333b4285"
): List<ShoppingCart>
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("http://localhost:4000/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
val frutasServices: Services = retrofit.create(Services::class.java)
My model:
package com.example.quitanda.models
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.parcelize.Parcelize
#Parcelize
data class ShoppingCart(
var count:Int=0,
#field:Json(name="product_title")
var name:String="",
#field:Json(name="product_id")
var id:Int=0,
#field:Json(name="photo_photo")
var photo:String="",
#field:Json(name="product_quant")
var quantidade:Int=0,
#field:Json(name="category_name")
var categoria:String="",
#field:Json(name="product_description")
var descricao:String="",
#field:Json(name="product_price_un")
var unidade:String="",
#field:Json(name="product_price_kg")
var kilo:String="",
var tipos:String=""): Parcelable
When I try to run my code it gives the following error
Does anyone have any idea how to fix this
who can help I am grateful
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quitanda, PID: 11031
java.lang.RuntimeException: Cannot create an instance of class com.example.quitanda.models.FrutasViewModel
I wouldn't recommend doing what you're trying to achieve, because what Android did, is that they've abstracted how viewmodels are scoped, to give you developers the power to easily handle things like orientation-change.
In practice this means, that android views, such as Activity/Fragment implement a ViewModelStoreOwner which contains a ViewModelStore, which handles the scoping and retrieves the correct ViewModel instance based on context.
TL;DR: If you want an android arch.viewmodel then create it in your Activity/Fragment and pass it to the EntryAbstract, though chances are you just need some of the data, which could be set individually for better separation of concerns

How to add Microsoft Word content in Email Body from Java Code

I am trying to put content of Microsoft Word Document in Email body from Java Code but getting following error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at co.kush.DemoEmail.main(DemoEmail.java:134)
Caused by: javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
at co.kush.DemoEmail.main(DemoEmail.java:128)
Caused by: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:896)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
Refer my code :
package co.kush;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.CharacterRun;
/**
* #author Kush
*
*/
public class DemoEmail {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop = new Properties();
String Filepath = "Email.Properties";
FileInputStream propFile = new FileInputStream(Filepath);
prop.load(propFile);
String timeStamp = new SimpleDateFormat("M/dd # HH:mm:ss").format(Calendar.getInstance().getTime());
// Fetching values from property file
String sender = prop.getProperty("sender");
String recevier = prop.getProperty("recevier");
String password = prop.getProperty("password");
String proxyHost = prop.getProperty("proxyHost");
String proxyPort = prop.getProperty("proxyPort");
String smtpHost = prop.getProperty("smtpHost");
String smtpPort = prop.getProperty("smtpPort");
String attachFilePath = prop.getProperty("attachFilePath");
String mailSubject=prop.getProperty("mailSubject")+" on " + timeStamp;
String mailBody = prop.getProperty("mailBody");
Properties sys_prop = System.getProperties();
// Setting values for sending Email
sys_prop.put("mail.smtp.starttls.enable", "true");
sys_prop.put("mail.transport.protocol", "SMTP");
sys_prop.put("mail.smtp.host", smtpHost);
sys_prop.put("mail.smtp.auth", "true");
sys_prop.put("mail.smtp.port", smtpPort);
sys_prop.put("mail.smtp.debug", "true");
sys_prop.put("mail.smtp.socketFactory.port", smtpPort);
sys_prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
sys_prop.put("mail.smtp.socketFactory.fallback", "false");
sys_prop.put("proxySet", "true");
sys_prop.put("proxyPort", proxyPort);
sys_prop.put("socksProxyHost", proxyHost);
sys_prop.put("proxyHost", proxyHost);
Session session = Session.getDefaultInstance(sys_prop, null);
try {
//Adding Sender/Receiver address and Subject Line
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recevier));
msg.setSubject(mailSubject);
MimeBodyPart messageBodyPart=new MimeBodyPart();
Multipart multipart = new MimeMultipart();
//Reading Word Document
HWPFDocument doc = new HWPFDocument(new FileInputStream("<AbsolutePathWordDoc\\<WordDocFile>.doc"));
WordExtractor we = new WordExtractor(doc);
String[] paragraphs = we.getParagraphText();
for (String para : paragraphs) {
//Putting word document to email Body
messageBodyPart.setContent(paragraphs, "application/msword");
multipart.addBodyPart(messageBodyPart);
}
//Adding attachment and Body content to MIME msg object
msg.setContent(multipart);
//Sending the message
Transport transport = session.getTransport("smtp");
transport.connect(smtpHost, sender, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Mail sent succesfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
//Removing System properties
sys_prop.remove("proxySet");
sys_prop.remove("proxyHost");
sys_prop.remove("proxyPort");
sys_prop.remove("socksProxyHost");
sys_prop.remove("mail.smtp.socketFactory.class");
sys_prop.remove("mail.smtp.socketFactory.fallback");
sys_prop.remove("mail.smtp.socketFactory.port");
}
}
}
Property file 'Email.Properties':
sender=helloqa86#gmail.com
recevier=k.b#xx.com
password=*****
proxyHost=web-proxy.**.**.com
proxyPort= 8080
smtpHost=smtp.gmail.com
smtpPort=465
From the error I can understand that problem is in this part
messageBodyPart.setContent(paragraphs, "application/msword"); where I am adding word document content to MIME message body part.
I have tried several other ways to achieve this but not able to do so. Please suggest a way to achieve this?
I got a resolution to this problem.Actually , I have to put different font face and font sizes in email body which I am trying to read from word document.To achieve this I have changed my approach,so instead of word document I have embedded my content into html tags which is quite simple :) , refer the below line of code which will replace word document part
String htmltext = "+
Different Font Size+
Different Font Size+
";
messageBodyPart.setContent(htmltext, "text/html");
During my research one of my friend suggested me following third party API's , it might be helpful to anyone
http://www.oracle.com/technetwork/java/javamail/third-party-136965.html
https://github.com/bbottema/simple-java-mail/

Why am I getting random errors in my Minecraft 1.7.10 mod using eclipse?

Sorry, I'm not sure if I'm in the right forum or if I'm wording it right. People may call this vague or something. I won't care.
Anyway, I've started to get random errors after trying something. It didn't turn out well. Here's the code + errors of my main mod file.
package com.harry.MoStuff;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
#Mod(modid = "ms", name = "Mo' Stuff", version = "a-1.0")
public class MoStuff {
public static Item itemRuby;
public static Item itemChain;
public static Item itemRubyEssence;
public static Item itemRubyShard;
public static Item itemRedBull;
public static Block blockRubyOre;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
//Item/block init and registering
//Config handling
itemRuby = new ItemRuby().setUnlocalizedName("ruby").setTextureName("ms:ruby");
itemChain = new ItemChain().setUnlocalizedName("chain");
blockRubyOre = new BlockRubyOre(Material.rock).setBlockName("ruby_ore").setBlockTextureName("ms:ruby_ore");
itemRubyShard = new ItemRubyShard().setUnlocalizedName("ruby_shard");
itemRubyEssence = new ItemRubyEssence().setUnlocalizedName("ruby_essence");
itemRedBull = new ItemFood(8, 1.0F, true).setUnlocalizedName("red_bull").setTextureName("ms:red_bull");
}
GameRegistry.registerItem(itemRuby, itemRuby.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemChain, itemChain.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRubyShard, itemRubyShard.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRubyEssence, itemRubyEssence.getUnlocalizedName().substring(5));
GameRegistry.registerBlock(blockRubyOre, blockRubyOre.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRedBull, itemRedBull.getUnlocalizedName().substring(5));
#EventHandler
public void init(FMLInitializationEvent event) {
//Proxy, tile entity, entity, GUI, packet reg.
GameRegistry.addRecipe(new ItemStack(itemRuby), new Object[]{"RRR","RRR","RRR", 'R', itemRubyShard});
GameRegistry.addRecipe(new ItemStack(itemChain), new Object[] {"III","I I","III", 'I', Items.iron_ingot});
GameRegistry.addRecipe(new ItemStack(itemRubyEssence, 5), new Object[]{" "," R "," ", 'R', itemRuby});
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
}
The errors are:
Multiple markers at this line (38, where GameRegistry.registerItem(itemRuby) and so on):
Syntax error on token ".", > expected.
Syntax error on token "(", < expected.
Syntax error on token ".", { expected.
Syntax error on token ")", delete this token.
Multiple markers at this line (46, where public void init(params) is.)
Syntax error on token "(", ; expected.
Syntax error on token ")", ; expected.
Multiple markers at this line (54, where public void postInit(params) is.)
Syntax error on token "(", ; expected.
Syntax error on token ")", ; expected.
That's all I can say. Thanks in advance.
On line 37, you closed the brace. Close it after all your GameRegistry.register

How to create an instance from string name?

Similar to this question, but I'm looking for a Haxe 3.0 solution. I'm looking to instantiate a class based on a a string (from my data file).
As far as I can tell this is correct. However, I get a runtime error
[Fault] exception, information=No such constructor npc.NPC_Squid
Fault, createEnum() at Type.hx:166
The Haxe 3 Code:
var e = haxe.macro.Expr.ExprDef;
var instance :Dynamic = e.createByName( "npc." + data.character, [] );
//....
My class:
package npc;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import openfl.Assets;
class NPC_Squid extends Sprite
{
public function new()
{
super();
addEventListener( Event.ADDED_TO_STAGE, onAdded);
addEventListener( Event.REMOVED_FROM_STAGE, onRemoved);
}
//....
My packages seem correct. Any ideas as to why it can't find the constructor?
I think you would need this:
var myInstance = Type.createInstance(Type.resolveClass("mypackage.MyClass"));
Note if you use dead-code elimination, you should import/reference MyClass somewhere.
I mostly create a function forceCompile in my Main class for such things:
public static function main()
{
forceCompile();
// Wind up all your stuff
}
public static function forceCompile()
{
MyClass;
}
In my Haxe 3 project, I use:
var easing: IEasing = Type.createEmptyInstance(Type.resolveClass("motion.easing." + easingType + easingStyle));
And it worked perfectly. One important precision: you need to import all the class that can be created this way. I imported all my motion.easing package to be sure.
You can see the full example here

eventhough i change the environmental variables and classpath, while running sqlite jdbc program i get the error stating no class definition doun

im running a jdbc program on Sqlite. though i change the environmental variables or define the classpath of the jar file sqlite-jdbc-3.7.2.jar, i get an error stating ClassNotFoundException: org.sqlite.JDBC... how to rectify it?
my code is`
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args)throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}`
my jar file is sqlite-jdbc-3.7.2.jar
my class path is D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar
my environmental variable is also the same
what should i do?
help pls
i found the solution to my problem...
the class path should be like
`javac Sample.java
java -classpath "D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar";. Sample`
the problem is solved:)

Resources