Posts Tagged ‘Oracle’
[DevoxxFR2013] JCP & Adopt a JSR Workshop
Lecturer
Patrick Curran chairs the Java Community Process (JCP), overseeing membership, processes, and Executive Committee. With over 20 years in software, including 15 at Sun, he led Java Conformance Engineering and chaired related councils. Active in W3C and OASIS.
Arun Gupta directs Developer Advocacy at Red Hat, focusing on JBoss Middleware. A Java EE founding member at Sun, he drove global adoption; at Oracle, he launched Java EE 7.
Mike Seghers, an IT consultant since 2001, specializes in Java enterprise web apps using frameworks like Spring, JSF. Experienced in RIA and iOS, he engages developer communities.
Abstract
Patrick Curran, Arun Gupta, and Mike Seghers’s workshop guides joining the Java Community Process (JCP) and participating in Adopt-a-JSR. They explain membership, transparency, and tools for JUG involvement like hackathons. Focusing on Java EE 8, the session analyzes collaboration benefits, demonstrating practical contributions for standard evolution.
Understanding JCP: Membership and Participation Pathways
Curran outlines JCP membership: free for individuals via jcp.org, requiring agreements; paid for corporations/non-profits ($2,000-$5,000). Java User Groups join as associates, nominating representatives.
Adopt-a-JSR encourages JUGs to engage JSRs: review specs, test implementations, provide feedback. This democratizes development, ensuring community input.
Gupta details Java EE 8 focus: HTML5, cloud, modularity. Adopt-a-JSR aids via mailing lists, issue trackers, wikis.
Practical Engagement: Tools and Initiatives for Collaboration
Tools include mailing lists for discussions, JIRA for bugs, GitHub for code. JUGs organize hack days, building samples.
Seghers demos Belgian JUG’s app: uses JSF, EJB, JPA for urban travelers game. Source on GitHub, integrates WebSockets.
This hands-on approach educates, uncovers issues early.
Case Studies: Global Adopt-a-JSR Impact
Examples: London JUG’s multiple JSR contributions; SouJava’s CDI focus; Morocco JUG’s hackathons. Chennai JUG built apps; Egypt JUG presented at conferences.
These illustrate visibility, skill-building, influence on standards.
Broader Implications: Enhancing Transparency and Community
JCP 2.8 mandates open Expert Groups, encouraging participation. Adopt-a-JSR amplifies this, benefiting platforms via diverse input.
Curran urges minimal commitments: feedback, testing. Gupta highlights launch opportunities.
Workshop fosters collaborative ecosystem, strengthening Java’s future.
Links:
[DevoxxFR2013] Regular or Decaffeinated? Java’s Future in the Cloud
Lecturer
Alexis Moussine-Pouchkine, a veteran of Sun Microsystems, currently serves as a Developer Relations lead at Google in Paris, assisting developers in achieving success. With over a decade at Sun and nearly two years at Oracle, he brings extensive experience in Java ecosystems and cloud technologies.
Abstract
Alexis Moussine-Pouchkine’s presentation examines Java’s evolution and its potential trajectory in cloud computing. Reflecting on historical shifts in technology, he critiques current limitations and advocates for advancements like multi-tenancy and resource management to ensure Java’s relevance. Through industry examples and forward-looking analysis, the talk underscores the need for adaptation to maintain Java’s position amid resource rationalization and emerging paradigms.
Java’s Maturation and the Cloud Imperative
Moussine-Pouchkine opens by recounting his transition from Sun Microsystems to Oracle and then Google, highlighting how each company has shaped computing history. At Sun, innovation abounded but market fit was inconsistent; Oracle emphasized acquisitions over novelty, straining community ties; Google prioritizes engineers, fostering rapid development.
He likens Java’s current state to emerging from adolescence, facing challenges in cloud environments where resource optimization is paramount. Drawing from his engineering school days with strict quotas on compilation and connection time, Alexis contrasts this with Java’s initial promise of freedom and flexibility. Early experiences with Linux provided boundless experimentation, mirroring Java’s liberating potential in 1997.
The speaker invokes historical predictions: IBM’s CEO allegedly foresaw a market for only five computers in 1943, possibly prescient regarding cloud providers. Bill Gates’ 640K memory quip and Greg Papadopoulos’ 2003 vision of five to seven massive global computers underscore consolidation trends. Papadopoulos envisioned entities like Google, eBay, Salesforce, Microsoft, Amazon, and a Chinese cloud, a perspective less radical today given web evolution.
Java’s centrality in tomorrow’s cloud is questioned. While present in many offerings, most implementations remain prototypes, circumventing Java’s constraints. The cloud demands shared resources and concentration of expertise, yet Java’s future here is uncertain, risking obsolescence like COBOL.
Challenges and Necessary Evolutions for Java in Multi-Tenant Environments
A core issue is Java’s adaptation to multi-tenancy, where multiple applications share a JVM without interference. Current JVMs lack robust isolation, leading to inefficiencies in cloud settings. Moussine-Pouchkine notes Java’s success in Android and Chrome, where processes are segregated, but enterprise demands shared instances for cost savings.
He critiques the stalled JSR-284 for resource management, essential for quotas and usage-based billing. Without these, Java lags in cloud viability. Examples like Google’s App Engine illustrate Java’s limitations: no threads, file system restrictions, and 30-second request limits, forcing workarounds.
Commercial solutions emerge: Waratek’s hypervisor on HotSpot, IBM’s J9 VM, and SAP’s container enable multi-tenancy. Yet, quotas remain crucial for responsible computing, akin to not overindulging at a buffet to ensure sustainability.
Java 9 priorities include modularity (Jigsaw), potentially aiding resource management. Cloud Foundry’s varying memory allocations by language highlight Java’s inefficiencies. Moussine-Pouchkine urges a “slider” for JVM scaling, from minimal to robust, without API fractures.
The community, pioneers in agile practices, continuous integration, and dependency management, must embrace modularity and quotas. Java 7 introduced dynamic languages; Java 8 tackles multicore with lambdas. Recent Oracle slides affirm multi-tenancy and resource management in Java 9 and beyond.
Implications for Sustainable and Credible Informatics
Moussine-Pouchkine advocates responsible informatics: quotas foster predictability, countering perceptions of IT as imprecise and costly. Developers, like artisans, must steward tools and design thoughtfully. Over-reliance on libraries (90% bloat) signals accumulated technical debt.
Quotas enhance credibility, enabling commitments and superior delivery. Java’s adaptive history positions it well, provided the community envisions it “caffeinated” – vibrant and adult – rather than “decaffeinated” and stagnant.
In essence, Java must address multi-tenancy and resources to thrive in consolidated clouds, avoiding the fate of outdated technologies.
Relevant Links and Hashtags
Links:
[DevoxxBE2012] On the Road to JDK 8: Lambda, Parallel Libraries, and More
Joseph Darcy, a key figure in Oracle’s JDK engineering team, presented an insightful overview of JDK 8 developments. With extensive experience in language evolution, including leading Project Coin for JDK 7, Joseph outlined the platform’s future directions, balancing innovation with compatibility.
He began by contextualizing JDK 8’s major features, particularly lambda expressions and default methods, set for release in September 2013. Joseph polled the audience on JDK usage, noting the impending end of public updates for JDK 6 and urging transitions to newer versions.
Emphasizing a quantitative approach to compatibility, Joseph described experiments analyzing millions of lines of code to inform decisions, such as lambda conversions from inner classes.
Evolving the Language with Compatibility in Mind
Joseph elaborated on the JDK’s evolution policy, prioritizing binary compatibility while allowing measured source and behavioral changes. He illustrated this with diagrams showing compatibility spaces for different release types, from updates to full platforms.
A core challenge, he explained, is evolving interfaces compatibly. Unlike classes, interfaces cannot add methods without breaking implementations. To address this, JDK 8 introduces default methods, enabling API evolution without user burden.
This ties into lambda support, where functional interfaces facilitate closures. Joseph contrasted this with past changes like generics, which preserved migration compatibility through erasure, avoiding VM modifications.
Lambda Expressions and Implementation Techniques
Diving into lambdas, Joseph defined them as anonymous methods capturing enclosing scope values. He traced their long journey into Java, noting their ubiquity in modern languages.
For implementation, Joseph rejected simple inner class translations due to class explosion and performance overhead. Instead, JDK 8 leverages invokedynamic from JDK 7, allowing runtime strategies like class spinning or method handles.
This indirection decouples binary representation from implementation, enabling optimizations. Joseph shared benchmarks showing non-capturing lambdas outperforming inner classes, especially multithreaded.
Serialization posed challenges, resolved via indirection to reconstruct lambdas independently of runtime details.
Parallel Libraries and Bulk Operations
Joseph highlighted how lambdas enable powerful libraries, abstracting behavior as generics abstract types. Streams introduce pipeline operations—filter, map, reduce—with laziness and fork-join parallelism.
Using the Fork/Join Framework from JDK 7, these libraries handle load balancing implicitly, encapsulating complexity. Joseph demonstrated conversions from collections to streams, facilitating scalable concurrent applications.
Broader JDK 8 Features and Future Considerations
Beyond lambdas, Joseph mentioned annotations on types and repeating annotations, enhancing expressiveness. He stressed deferring decisions to avoid constraining future evolutions, like potential method reference enhancements.
In summary, Joseph portrayed JDK 8 as a coordinated update across language, libraries, and VM, inviting community evaluation through available builds.
Links:
[DevoxxFR2012] 55 Lesser-Known Features of Java 7: Unveiling Hidden Enhancements Across the Platform
Lecturer
David Delabassee serves as a Director of Developer Relations in the Java Platform Group at Oracle, where he champions Java technologies worldwide through presentations, technical articles, and open-source engagements. Previously at Sun Microsystems for a decade, he focused on end-to-end Java implementations, from smart cards to high-end servers. A member of the Devoxx Belgium steering committee, David co-hosts the Inside Java Podcast and maintains a blog at delabassee.com. He holds Belgian nationality and has spoken at numerous conferences and Java User Groups.
Abstract
This article investigates David Delabassee’s rapid-fire presentation on 55 underappreciated features of Java 7, released in 2011, extending beyond well-known additions like Project Coin, Fork/Join, NIO.2, and invokedynamic. It categorizes enhancements across core libraries, security, internationalization, graphics, and more, analyzing their practical utilities and implementation details. Positioned as a post-Sun acquisition milestone under Oracle, the discussion evaluates how these refinements bolster platform stability, performance, and developer productivity. Through code demonstrations and comparisons to prior versions, it assesses implications for migration, legacy code maintenance, and modern application design, emphasizing Java 7’s role in bridging to future iterations like Java 8.
Core Language and Library Improvements
Java 7 introduced subtle yet impactful tweaks to foundational elements, addressing longstanding pain points. David highlights enhanced exception handling: multi-catch clauses consolidate try-catch blocks for related exceptions, reducing redundancy:
try {
// Code
} catch (IOException | SQLException e) {
// Handle
}
String switches leverage interned strings for efficient comparisons, useful in parsing:
switch (input) {
case "start": // Action
break;
// ...
}
Underscores in numeric literals improve readability for large numbers: long creditCard = 1234_5678_9012_3456L;.
Library updates include Objects class utilities like requireNonNull() for null checks, and BitSet enhancements with valueOf() for byte/long array conversions. These foster cleaner, more maintainable code, mitigating common errors in enterprise applications.
Security and Cryptography Advancements
Security received substantial bolstering, crucial amid rising threats. David details elliptic curve cryptography integration, offering stronger keys with smaller sizes for SSL/TLS. Algorithm disabling via jdk.security.provider.disabledAlgorithms property enhances compliance.
SChannel provider on Windows improves native integration, while JSSE updates support SNI for virtual hosting. These fortify networked applications, essential for cloud and web services, reducing vulnerability exposure without external libraries.
Internationalization and Locale Refinements
Java 7 refined locale handling for global apps. Unicode 6.0 support adds scripts like Batak, enhancing text processing. Locale enhancements include script, variant, and extension keys:
Locale loc = new Locale.Builder().setLanguage("fr").setRegion("FR").setScript("Latn").build();
Currency updates reflect ISO 4217 changes, with getAvailableCurrencies() listing supported ones. NumberFormat improvements allow custom symbols, aiding financial software. These ensure accurate, culturally sensitive representations, vital for international markets.
Graphics and UI Toolkit Upgrades
Swing and AWT saw usability boosts. Translucent/shaped windows via GraphicsDevice enable modern UIs:
window.setOpacity(0.5f);
Nimbus look-and-feel, now default in some contexts, provides scalable, themeable components. JLayer adds decoration layers for effects like blurring. These empower richer desktop apps, aligning Java with contemporary design trends.
Performance and JVM Optimizations
JVM internals evolved for efficiency. Tiered compilation combines client/server compilers for faster startups and peak performance. G1 garbage collector, experimental in Java 7, targets low-pause collections for large heaps.
Compressed oops extend 32-bit addressing to 64-bit, reducing memory footprint. These optimizations benefit server-side applications, improving throughput and responsiveness in high-load scenarios.
Migration Considerations and Ecosystem Impact
Adopting Java 7 involves assessing compatibility, given end-of-life for Java 6. David notes seamless transitions for most code, but highlights needs like updating deprecated APIs. Tools like javac -Xlint warn of issues.
Ecosystem-wise, Java 7 paved for Java 8’s lambdas, solidifying Java’s enterprise dominance. Implications include smoother upgrades, enhanced security postures, and broader internationalization, encouraging developers to leverage these for robust, future-proof systems.
Links:
Error grabbing Grapes — [unresolved dependency: com.oracle#ojdbc14;10.2.0.4.0: not found]
I have learnt Groovy since the beginning of the week.
I had to import some classes from Oracle JDBC driver. As a newbie, I wrote the following annotation:
[java]@Grab(group = ‘com.oracle’, module = ‘ojdbc14’, version = ‘10.2.0.4.0’)[/java]
I got the following error:
[java]Error grabbing Grapes — [unresolved dependency: com.oracle#ojdbc14;10.2.0.4.0: not found][/java]
To sum up, adding a dependency to Oracle driver raises two issues:
- adding any external dependency
- adding a dependency to any JDBC driver
Indeed, Grab requires a kind of Maven repository, and you can catch the link between the @Grab annotation below and classic Maven 2 <dependency> tag. As I understood, Grab instructions are closer to Ivy than to Maven system. In my situation, having no “Grab repo” (I don’t know how to call that), I had to download the jars from a Maven repo. To fix it, two operations are needed: hint at Maven (or Ivy) repo, and allow Groovy to access the network.
Regarding the second issue, it is answered by added a @GrabConfig annotation.
Therefore, to fix the original issue:
-
replace [java]@Grab(group = ‘com.oracle’, module = ‘ojdbc14’, version = ‘10.2.0.4.0’)[/java]
with[java]@GrabConfig(systemClassLoader=true)
@GrabResolver(name=’nameOfYourMavenRepo, root=’http://url-of-your-maven-repo:port’)
@Grab(group = ‘com.oracle’, module = ‘ojdbc14’, version = ‘10.2.0.4.0’)
[/java] - at first run, if needed, hint at the proxy to allow Grab to download the Jars, eg: [java]groovy -Dhttp.proxyHost=myProxyHost -Dhttp.proxyPort=8080[/java]
You may notice the needed JAR will be written in the $USER_HOME/.groovy/grapes folder.
How to export Oracle DB content to DBUnit XML flatfiles?
Case
From an Agile and TDD viewpoint, performing uni tests on DAO is a requirement. Sometimes, instead of using DBUnit datasets “out of the box”, the developper need test on actual data. In the same vein, when a bug appears on production, isolating and reproducing the issue is a smart way to investigate, and, along the way, fix it.
Therefore, how to export actual data from Oracle DB (or even MySQL, Sybase, DB2, etc.) to a DBUnit dataset as a flat XML file?
Here is a Runtime Test I wrote on this subject:
Fix
Spring
Edit the following Spring context file, setting the login, password, etc.
[xml]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!– don’t forget to write this, otherwise the application will miss the driver class name, and therfore the test will fail–>
<bean id="driverClassForName" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.Class"/>
<property name="targetMethod" value="forName"/>
<property name="arguments">
<list>
<value>oracle.jdbc.driver.OracleDriver</value>
</list>
</property>
</bean>
<bean id="connexion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
depends-on="driverClassForName">
<property name="targetClass" value="java.sql.DriverManager"/>
<property name="targetMethod" value="getConnection"/>
<property name="arguments">
<list>
<value>jdbc:oracle:thin:@host:1234:SCHEMA</value>
<value>myLogin</value>
<value>myPassword</value>
</list>
</property>
</bean>
<bean id="databaseConnection" class="org.dbunit.database.DatabaseConnection">
<constructor-arg ref="connexion"/>
</bean>
<bean id="queryDataSet" class="org.dbunit.database.QueryDataSet">
<constructor-arg ref="databaseConnection"/>
</bean>
</beans>[/xml]
The bean driverClassForName does not look to be used ; anyway, if Class.forName("oracle.jdbc.driver.OracleDriver") is not called, then the test will raise an exception.
To ensure driverClassForName is created before the bean connexion, I added a attribute depends-on="driverClassForName". The other beans will be created after connexion, since Spring will deduce the needed order of creation via the explicit dependency tree.
Java
[java]public class Oracle2DBUnitExtractor extends TestCase {
private QueryDataSet queryDataSet;
@Before
public void setUp() throws Exception {
final ApplicationContext applicationContext;
applicationContext = new ClassPathXmlApplicationContext(
"lalou/jonathan/Oracle2DBUnitExtractor-applicationContext.xml");
assertNotNull(applicationContext);
queryDataSet = (QueryDataSet) applicationContext.getBean("queryDataSet");
}
@Test
public void testExportTablesInFile() throws DataSetException, IOException {
// add all the needed tables ; take care to write them in the right order, so that you don’t happen to fall on dependencies issues, such as ones related to foreign keys
queryDataSet.addTable("MYTABLE");
queryDataSet.addTable("MYOTHERTABLE");
queryDataSet.addTable("YETANOTHERTABLE");
// Destination XML file into which data needs to be extracted
FlatXmlDataSet.write(queryDataSet, new FileOutputStream("myProject/src/test/runtime/lalou/jonathan/output-dataset.xml"));
}
}[/java]
How to populate/insert/update a CLOB larger than 4000 or 32767 bytes?
A Short String
I have a table of which one field is a CLOB. Let’s say I have to insert one record with a short text. The following command is allowed:
[sql]INSERT INTO jonathan_table VALUES (1, ‘hello world!’);[/sql]
A Bigger Text
Error ORA-01704
Now, my text is larger, let’s say 5000 characters. When I launch the same query, I get the following error:
[sql]ORA-01704: string literal too long[/sql]
Indeed, Oracle/SQL*Plus have a limit on CLOB inserts: 4000 bytes.
Workaround
To pass through the limit on canonical SQL, you’ll have to use a PL/SQL procedure. The following command will be successful for any text larger than 4000 bytes, but shorter than 32767:
[sql]DECLARE
bigtext1 VARCHAR2 (32767);
BEGIN
bigtext1 := lpad(‘X’, 32000, ‘X’)
INSERT INTO jonathan_table VALUES (1, bigtext1);
END;[/sql]
An Even Bigger Text
Errors ORA-06550 and PLS-00103
You guess it: beyond this limit of 32 KB, an error occurs. So the following script:
[sql]DECLARE
bigtext1 VARCHAR2 (42000);
BEGIN
bigtext1 := lpad(‘X’, 42000, ‘X’)
INSERT INTO jonathan_table
VALUES (1, bigtext1);
END;
[/sql]
raises such an error:
[sql]Error at line 1
ORA-06550: line 5, column 4:
PLS-00103: Encountered the symbol "INSERT" when expecting one of the following:
. ( * % & = – + ; < / > at in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec between || multiset member submultiset
The symbol ";" was substituted for "INSERT" to continue.[/sql]
Fix this issue
I searched a lot to find an easy fix to go beyond the limit of 32KB. My point was that with Java for instance there is no limit of 32KB. In the same way, with TOAD I was able to update the record with many mega bytes of text, via the clipboard. After further search, I learnt that the 32KB barrier was a SQL*Plus limitation on actual strings, but the patterns insert into ... select ... from were not affected.
Here is the idea:
- create a temporary table
- split the text into blocks shorter than 32KB
- insert the blocks into the temporary table
- perform a first insert with a null CLOB
- update the record using a
selecton the temporary table (yet you can insert the actual value since previous step)
Here is an example:
[sql]DROP TABLE tt_jonathan_table;
CREATE GLOBAL TEMPORARY TABLE tt_jonathan_table
(
ID NUMBER(10),
pdlsuffix CLOB
) ON COMMIT PRESERVE ROWS;
TRUNCATE TABLE tt_jonathan_table;
DECLARE
bigtext1 VARCHAR2 (32767);
bigtext2 VARCHAR2 (32767);
BEGIN
bigtext1 := lpad(‘X’, 32000, ‘X’)
bigtext2 := lpad(‘Y’, 32000, ‘Y’)
INSERT INTO tt_jonathan_table
VALUES (1, bigtext1);
INSERT INTO tt_jonathan_table
VALUES (2, bigtext2);
INSERT INTO jonathan_table
(id, myClobField)
VALUES (jonathan_seq.NEXTVAL, NULL);
UPDATE jonathan_table
SET myClobField = (SELECT CONCAT (rls1.myClobField, rls2.myClobField)
FROM tt_jonathan_table rls1, tt_jonathan_table rls2
WHERE rls1.ID = 1 AND rls2.ID = 2)
WHERE myClobField is null;
END;
/
TRUNCATE TABLE tt_jonathan_table;
[/sql]
How to Read a BLOB for a Human Being?
Case
I have had to access a BLOB and read its content. By principle, I dislike using binary objects, which do not suit easy tracing and auditing. Anyway, in my case, floats are stored in a BLOB, and I need read them in order to validate my current development.
You have many ways to read the content of the BLOB. I used two: SQL and Java
SQL
Start your TOAD for Oracle ; you can launch queries similar to this:
[sql]SELECT UTL_RAW.cast_to_binary_float
(DBMS_LOB.submyrecord (myrecord.myrecordess,
4,
1 + (myrecordessnameid * 4)
)
) AS myrecordessvalue
FROM mytable myrecord
WHERE myrecordessid = 123456; [/sql]
You can also run a stored procedure, similar to this:
[sql]
DECLARE
blobAsVariable BLOB;
my_vr RAW (4);
blobValue FLOAT;
bytelen NUMBER := 4;
v_index NUMBER := 5;
jonathan RAW (4);
loopLength INT;
BEGIN
SELECT myField
INTO blobAsVariable
FROM myTable
WHERE tableid = (5646546846);
DBMS_LOB.READ (blobAsVariable, bytelen, 1, jonathan);
loopLength := UTL_RAW.cast_to_binary_integer (jonathan);
FOR rec IN 1 .. loopLength
LOOP
DBMS_LOB.READ (blobAsVariable, bytelen, v_index, my_vr);
blobValue := UTL_RAW.cast_to_binary_float (my_vr);
v_index := v_index + 4;
DBMS_OUTPUT.put_line (TO_CHAR (blobValue));
END LOOP;
END;[/sql]
Java
I am still not sure to be DBA expert. Indeed I am convinced I am more fluent in Java than in PL/SQL 😉
Create a Spring configuration file, let’s say BlobRuntimeTest-applicationContext.xml:
[xml]<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!– $Id: BlobRuntimeTest-applicationContext.xml $ –>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@myDBserver:1234:MY_SCHEMA"/>
<property name="username" value="jonathan"/>
<property name="password" value="lalou"/>
<property name="initialSize" value="2"/>
<property name="minIdle" value="2"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>[/xml]
Now create a runtime test:
[java]/**
* User: Jonathan Lalou
* Date: Aug 7, 2011
* Time: 5:22:33 PM
* $Id: BlobRuntimeTest.java $
*/
public class BlobRuntimeTest extends TestCase {
private static final Logger LOGGER = Logger.getLogger(BlobRuntimeTest.class);
private static final String TABLE = "jonathanTable";
private static final String PK_FIELD = "jonathanTablePK";
private static final String BLOB_FIELD = "myBlobField";
private static final int[] PK_VALUES = {123, 456, 789};
private ApplicationContext applicationContext;
private JdbcTemplate jdbcTemplate;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext(
"lalou/jonathan/the/cownboy/BlobRuntimeTest-applicationContext.xml");
assertNotNull(applicationContext);
jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
assertNotNull(jdbcTemplate);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGetArray() throws Exception {
for (int pk_value : PK_VALUES) {
final Blob blob;
final byte[] bytes;
final float[] floats;
blob = (Blob) jdbcTemplate.queryForObject("select " + BLOB_FIELD + " from " + TABLE + " where " + PK_FIELD + " = " + pk_value, Blob.class);
assertNotNull(blob);
bytes = blob.getBytes(1, (int) blob.length());
// process your blob: unzip, read, concat, add, etc..
// floats = ….
LOGGER.info("Blob size: " + floats.length);
LOGGER.info(ToStringBuilder.reflectionToString(floats));
}
}
}
[/java]
java.sql.SQLException: Wrong data type: NUMBER in statement [CREATE TABLE … (… NUMBER]
Case
In a JDBC DAO, I execute a query to retrieve an object. I get this error:
[java]java.sql.SQLException: Wrong data type: NUMBER in statement [CREATE TABLE Jonathan_Table (TableColumn NUMBER][/java]
Stacktrace
[java]java.sql.SQLException: Wrong data type: NUMBER in statement [CREATE TABLE Jonathan_Table (TableColumn NUMBER]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at com.bnpp.pb.risklayer.services.dao.jdbc.JdbcPrimeRiskServerDaoUnitTest.getDataSet(JdbcPrimeRiskServerDaoUnitTest.java:57)
at org.dbunit.DatabaseTestCase.setUp(DatabaseTestCase.java:154)[/java]
Explanation and fix
My original DB is under Oracle, but my DBUnit tests works on HSQL. Yet, types NUMBER and VARCHAR2 are not available under HSQL, this is why the exception is raised.
To fixe the issue, rewrite your scripts, replacing NUMBER and VARCHAR2 with NUMERIC and VARCHAR.
Oracle / OUI-10038
Case
Trying to install Oracle Agent on a Windows XP SP2 desktop, I get the following error:
[java]ERROR: OUI-10038:You do not have the necessary permissions to write to the inventory at \Oracle\Inventory. Please make sure that you have the appropriate permissions to perform the installation.[/java]
Fix
Edit the registry. For the key HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\inst_loc, replace the value \Oracle\Inventory with C:\Oracle\Inventory