Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Tuesday, September 24, 2013

weblog; hello, raspberry pi

Rails

ruby on rails - Routing to static html page in /public - Stack Overflow

http://stackoverflow.com/questions/5631145/routing-to-static-html-page-in-public

Tried to host wsdl and xsd resources. This seemed to be more trouble than it was worth, so I turned to Rack to get the job done. That being said, I decided it would be more consistent to simple grab resources relatively from the file system.

Rails Routing from the Outside In — Ruby on Rails Guides

http://guides.rubyonrails.org/routing.html

I was trying to figure out how to redirect to a static page. This didn't end up helping. Ended up using Rack instead.

get '/stories', to: redirect('/posts')

get '/stories/:name', to: redirect('/posts/%{name}')

get '/stories/:name', to: redirect {|params, req| "/posts/#{params[:name].pluralize}" }

get '/stories', to: redirect {|p, req| "/posts/#{req.subdomain}" }

Layouts and Rendering in Rails — Ruby on Rails Guides

http://guides.rubyonrails.org/layouts_and_rendering.html

Tried to render xml and xsd files. Again, I ended up using Rack instead.

render xml: @product

render file: filename, content_type: "application/rss"

How can I get a rails route to keep the extension as part of the id? - Stack Overflow

http://stackoverflow.com/questions/3409395/how-can-i-get-a-rails-route-to-keep-the-extension-as-part-of-the-id
  • http://stackoverflow.com/questions/948886/rails-restful-resources-using-to-param-for-a-field-that-contains-separator-chara
  • http://poocs.net/2007/11/14/special-characters-and-nested-routes

At first, I was having success with rendering the wsdl, but the xsd files have periods throughout the file name. I wanted to be able to ignore the periods, but Rails thought what followed the period was the file extension.

map.resources :websites, :requirements => { :id => /[a-zA-Z0-9\-\.]+/ } do |websites|
    websites.with_options :requirements => { :website_id => /[a-zA-Z0-9\-\.]+/ }  do |websites_requirements|
        websites_requirements.resources :dns_records
    end
end

map.resources :users,
  :requirements => { :id => %r([^/;,?]+) }

For Rails3 use :constraints instead of :requirements

http://stackoverflow.com/questions/3409395/how-can-i-get-a-rails-route-to-keep-the-extension-as-part-of-the-id

Ruby on Rack #1 - Hello Rack! - (m.onkey.org)

http://m.onkey.org/ruby-on-rack-1-hello-rack

Lovely, little lightweight web server. I ended up using this instead of Rails to host wsdl and xsd resources.

require 'rubygems'
require 'rack'

class HelloWorld
  def call(env)
    [200, {"Content-Type" => "text/html"}, "Hello Rack!"]
  end
end

Rack::Handler::Mongrel.run HelloWorld.new, :Port => 9292

Maven

jax ws - Use CXF JaxWsServerFactoryBean exception Cannot find any registered HttpDestinationFactory from the Bus - Stack Overflow

http://stackoverflow.com/questions/13617691/use-cxf-jaxwsserverfactorybean-exception-cannot-find-any-registered-httpdestinat
Caused by: java.io.IOException: Cannot find any registered HttpDestinationFactory from the Bus.
        at org.apache.cxf.transport.http.HTTPTransportFactory.getDestination(HTTPTransportFactory.java:295)
        at org.apache.cxf.binding.soap.SoapTransportFactory.getDestination(SoapTransportFactory.java:143)
        at org.apache.cxf.endpoint.ServerImpl.initDestination(ServerImpl.java:93)
        at org.apache.cxf.endpoint.ServerImpl.<init>(ServerImpl.java:72)
        at org.apache.cxf.frontend.ServerFactoryBean.create(ServerFactoryBean.java:160)

If this error is logged, check and make sure the Jetty library is in the classpath.

 <dependencies>

    ...

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http-jetty</artifactId>
      <version>2.7.6</version>
    </dependency>
 </dependencies>

SLF4J Error Codes

http://www.slf4j.org/codes.html#StaticLoggerBinder

Apparently, there are way too many logging libraries. Unfortunately, some libraries package in their own perferred logging library. This poses some challenges when there are conflicts. I had to disable a javadoc generator plugin because it bundled a logging library that was compatible with another logging library in a different JAR resource.

Do your best to exclude those libraries causing conflicts.

Check the dependency tree and add excludes.
mvn dependency:tree -Dincludes=velocity:velocity
Next, exclude inner dependencies. And then if you have to, remove libraries that bundle too much for their own good.
<dependencies>

  ..

  <dependency>
    <groupId>org.apache.maven.plugin-tools</groupId>
    <artifactId>maven-plugin-tools-api</artifactId>
    <version>2.5.1</version>

    <exclusions>
      <exclusion>
        <groupId>jetty</groupId>
        <artifactId>jetty</artifactId>
      </exclusion>
    </exclusions>

  </dependency>
</dependencies>

Maven Repository: ch.qos.logback » logback-classic

» 1.0.13 http://mvnrepository.com/artifact/ch.qos.logback/logback-classic/1.0.13

Dependency entry for logback logging library. There are so many logging libraries out there; this one seems to have a greater level of popularity.


 ch.qos.logback
 logback-classic
 1.0.13

Logback should be used in conjunction with SLF4J.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;

public class HelloWorld2 {

  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld2");
    logger.debug("Hello world.");

    // print internal state
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    StatusPrinter.print(lc);
  }
}

Logback is intended as a successor to the popular log4j project. [It] is faster and has a smaller footprint than all existing logging systems...

http://mvnrepository.com/artifact/ch.qos.logback/logback-classic/1.0.13

Maven - Introduction to the Build Lifecycle

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

Without understanding the Maven lifecycle, you will be navigating the waters of Maven blindly.

java - Different dependencies for different build profiles in maven - Stack Overflow

http://stackoverflow.com/questions/166895/different-dependencies-for-different-build-profiles-in-maven

Each profile block supports the tag

<profiles>
    <profile>
     <id>debug</id>
     …
     <dependencies>
      <dependency>…</dependency>
     </dependencies>
     …
    </profile>
    <profile>
     <id>release</id>
     …
     <dependencies>
      <dependency>…</dependency>
     </dependencies>
     …
    </profile>
</profiles>

Maven Repository: org.apache.cxf » cxf-rt-transports-http-jetty

» 2.7.6 http://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http-jetty/2.7.6

Dependency entry for the Jetty web server library.

<dependency>
 <groupId>org.apache.cxf</groupId>
 <artifactId>cxf-rt-transports-http-jetty</artifactId>
 <version>2.7.6</version>
</dependency>

Maven Dependency plugin - Filtering the dependency tree

http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html
  • http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html

When there are problems with dependencies, this is a vital tool to get some insight and resolve the problem. Sometimes those issues can be resolved by including an <excludes> block. Other times dependencies need to be moved around, either in a different order in a given pom.xml or moved into a different pom.xml altogether.

Maven Repository: org.apache.maven.plugins » maven-javadoc-plugin » 2.9.1

http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-javadoc-plugin/2.9.1
  • https://bitbucket.org/atlassian/maven-javadoc-plugin
  • http://stackoverflow.com/questions/tagged/maven-javadoc-plugin

Got to get my Javadocs up to par...

<dependency>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-javadoc-plugin</artifactId>
 <version>2.9.1</version>
</dependency>

Versions Maven Plugin - Checking for new plugin updates

http://mojo.codehaus.org/versions-maven-plugin/examples/display-plugin-updates.html

The display-plugin-updates goal will check all the plugins and reports used in your project and display a list of those plugins with newer versions available.

mvn versions:display-plugin-updates

CXF

Developing Web services using Apache CXF and Maven

http://www.ctrl-alt-dev.nl/Articles/CXF-Maven/CXF-Maven.html

Step-by-step instructions on how to develop a web service using CXF and Maven. Starts off by creating a web service without CXF, adds tests and then replaces non-test code with code generated by CXF. Should be a worth while walkthrough.

Java

How to get the filepath of a file in Java

http://www.mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/

Get the full path for a given file. Needed this for my Rails to static page html converter.

File file = File("C:\\abcfolder\\textfile.txt");
System.out.println("Path : " + file.getAbsolutePath());

Frequently Asked Questions about SLF4J

http://slf4j.org/faq.html

I need to get to know the SLF4J logging library a little better since it appears Log4j is ancient now.

Hibernate Annotations

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/

Authoritative reference on Hibernate annotations. With this, we don't have to juggle hundreds of Hibernate configuration files. The Hibernate configuration is combined with the java code that defines the DAOs.

CSS text-decoration property

http://www.w3schools.com/cssref/pr_text_text-decoration.asp

Needed a reminder on how to implement strike-through

h2 {text-decoration:line-through}

UCPath

UCPath:System Design:Interface FDDs

https://sp2010.ucop.edu/sites/ucpath/System%20Design/Forms/AllItems.aspx?Paged=TRUE&p_SortBehavior=0&p_FileLeafRef=DS%20140%20Functional%20Design%20I%2d601%20CONEXIS%20DirectBill%20OB%2edocx&p_ID=148&RootFolder=%2fsites%2fucpath%2fSystem%20Design%2fInterface%20FDDs&PageFirstRow=91&TreeField=Folders&TreeValue=Interface%20FDDs&ProcessQStringToCAML=1&&View={B1F1C4C1-3FDB-400F-9D41-942503D1AF92}

Functional design documents.

Raspberry Pi

CoolGear® USB 3.0 to SATA and IDE Hard Drive Adapter Universal 2.5/3.5/5.25 Drives

open http://www.amazon.com/gp/product/B009VKSNS6/ref=oh_details_o04_s00_i00?ie=UTF8&psc=1 http://www.amazon.com/gp/product/B009VKSNS6/ref=oh_details_o04_s00_i00?ie=UTF8&psc=1
  • http://www.amazon.com/SATA-Drive-Adapter-Universal-Drives/dp/B004FEQ8MG

Device that can be used to rescue data from an external or internal hard drive due to an interface gone bad. This saved many, many of my wife's photos. They were not corrupt; the hard drive simply wouldn't mount due to a faulty interface.

Check out this video for instructions on how to use the device to rescue your files.

Apache CXF -- JAX-WS Configuration

http://cxf.apache.org/docs/jax-ws-configuration.html

Configuring an Endpoint. This Spring configuration handles setting up the webservice so we don't have to write the Java code. Thank you, Apache CXF.

<jaxws:endpoint id="classImpl"
    implementor="org.apache.cxf.jaxws.service.Hello"
    endpointName="e:HelloEndpointCustomized"
    serviceName="s:HelloServiceCustomized"
    address="http://localhost:8080/test"
    xmlns:e="http://service.jaxws.cxf.apache.org/endpoint"
    xmlns:s="http://service.jaxws.cxf.apache.org/service"/>

The Only Raspberry Pi XBMC Tutorial You Will Ever Need

http://mymediaexperience.com/raspberry-pi-xbmc-with-raspbmc/

If I get around to building a home network, this is how I will cut my teeth on a Raspberry Pi.

Raspberry Pi

NETGEAR G54/N150 WiFi USB Micro Adapter WNA1000M | Staples®

http://www.staples.com/NETGEAR-G54-N150-WiFi-USB-Micro-Adapter-WNA1000M/product_927666?cid=PS:GooglePLAs:927666&KPID=927666
  • http://www.superbiiz.com/detail.php?p=IMTW311M&c=fr&pid=36a601e944c3b844313893c45c178493ad8db092420bcb54ace3c24f8cdbcf68&gclid=CNvytr7M3LkCFeV7QgodPUwA1w
  • http://www.monoprice.com/products/product.asp?seq=1&format=2&p_id=6146&CAWELAID=1329452226&catargetid=320013720000011065&cadevice=c&cagpspn=pla&gclid=CPSX6K7M3LkCFUSCQgodvmEABw
  • http://www.amazon.com/USB-Wireless-Lan-Adapter-150Mbps/dp/B002XGDU9M

Use this (or something like unto it) to provide wifi for a Raspberry Pi.

Language

Google Translate

http://translate.google.com/#pt/en/celebrar

When I need a little help with my Spanish or Portuguese.

Google Translate

Thursday, September 5, 2013

weblog; cucumber, hibernate and certificates

Cucumber

Github: cucumber/cucumber-jvm

https://github.com/cucumber/cucumber-jvm http://cukes.info/install-cucumber-jvm.html https://github.com/cucumber/cucumber-jvm/tree/master/examples/java-helloworld

Cucumber-JVM is a pure Java implementation of Cucumber that supports the most popular programming languages for the JVM.

https://github.com/cucumber/cucumber-jvm

Hibernate

How do we count rows using Hibernate?

http://stackoverflow.com/questions/1372317/how-do-we-count-rows-using-hibernate
Integer count = (Integer) session.CreateQuery("select count(*) from Books").UniqueResult();

Where 'Books' is the name off the class - not the table in the database.

hibernate.connection.autocommit

https://forum.hibernate.org/viewtopic.php?f=1&t=944848

It sounds like it's a good idea not to turn on auto-commit.

JPA + Hibernate + autocommit

http://stackoverflow.com/questions/1228086/jpa-hibernate-autocommit

The syntax is slightly different for the version of Hibernate I'm using.

NO!
<property name="hibernate.connection.autocommit" value="false"/>

Yes
<property name="hibernate.connection.autocommit">false</property>

remaining connection slots are reserved for non-replication superuser connections

http://community.webfaction.com/questions/12239/remaining-connection-slots-are-reserved-for-non-replication-superuser-connections http://stackoverflow.com/questions/5108876/kill-a-postgresql-session-connection

Manually locate the hanging Postres processes and kill them.

" extract pids from list of  processes
" after running 'ps -ef|grep postgres'
:%s/  \d\+ \(\d\+\) .\+\n\+/ \1/g

Supposedly, a similar outcome can be achieved with this query to the database:

"Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:
REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;

"Let us begin...
SELECT 
    pg_terminate_backend(pid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    pid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

org.hibernate Interface Session

http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html#method_summary http://stackoverflow.com/questions/4588406/replacing-existing-rows-with-new-ones-causes-duplicate-key-exception

When in doubt, read the documentation. There are several things I learned here.

#evict: even after deleting a record, the identifier is still in the cache. Perhaps I ran into this problem because I hadn't closed the session yet or called #commit. Perhaps #evict was a better decision for performance sake in my particular case setting up my integration test.

#rollback: the Session#beginTransaction -> Transaction#commit block does not automatically issue a #rollback if an exception is thrown. You will need to capture exceptions and manually issue a rollback.

#persist: saves a record to the database; not sure if it is supposed to be used for updating, but I use it to save records to the database and use the identifier that I supply. #save will attempt to generate an id before data is persisted to the database.

#flush: queries are queued and reordered in a given transaction. Insert statements come before delete statements, so even if a delete statement is coded before the insert statement, when #commit is invoked, the insert will still come before the delete. Using flush in the transaction tells Hibernate to execute all queries currently in the queue before handling the remaining statements in the transaction. And yes, a #rollback will rollback code both before the #flush and after as long as it is still between the Session#beginTransaction and Transaction#commit.

A typical transaction should use the following idiom:

 Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html#method_summary

SSL and Certificates

Steps to create a csr using keytool and sign with verisign

http://wls4mscratch.wordpress.com/2010/06/08/steps-to-create-a-csr-and-sign-with-verisign/ http://mihail.stoynov.com/2009/03/12/certificates-keystores-java-keytool-utility-and-openssl/
keytool -genkey -alias server -keyalg RSA -sigalg SHA1withRSA -keysize 4096 -keystore server.jks -dname "CN=server, OU=Some Organization, O=Some Office, L=Some City, ST=CA, C=US" -validity 1095 -storepass $STORE_PASS

keytool -certreq -alias server -keystore server.jks -storepass $STORE_PASS > server.csr

keytool - Key and Certificate Management Tool

http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/keytool.html

Comprehensive documentation on how to use keytool.

[K]eytool is a key and certificate management utility. It allows users to administer their own public/private key pairs and associated certificates for use in self-authentication... or data integrity and authentication services, using digital signatures.

Tuesday, September 3, 2013

weblog; Hibernate, PostgreSql, Maven, JRuby

Hibernate

Hibernate opening/closing session, the correct approach for DAO

http://stackoverflow.com/questions/8841207/hibernate-opening-closing-session-the-correct-approach-for-dao

Experiencing problems with session, I think. After deleting records from the database, should the session be closed and opened again to stop getting exceptions?

Hibernate Error: a different object with the same identifier value was already associated with the session

http://stackoverflow.com/questions/16246675/hibernate-error-a-different-object-with-the-same-identifier-value-was-already-a

It seems this is where I'm having my current code hangup. Should I be closing the session between deletes and inserts? Or is there something being updated instead and that's throwing exceptions because I'm inadvertently attempting to update a record that has been destroyed in the same session?

PostgreSql

PostgreSQL: Get the second to last MAX(date)

http://stackoverflow.com/questions/16567632/postgresql-get-the-second-to-last-maxdate

Maven

Maven: Filtering the dependency tree

http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html http://maven.apache.org/plugins/maven-dependency-plugin/examples/resolving-conflicts-using-the-dependency-tree.html
mvn dependency:tree -Dincludes=velocity:velocity
mvn dependency:tree -Dverbose -Dincludes=commons-collections

I used this to resolve issues I was experiencing with log jars. I was including a version of one collection of jars. Another resource was pulling them in too, only a different version. This was raising some warnings anytime I ran maven. I used a call like this one to figure our where my conflicts existed.

JRuby

JRuby and Java Code Examples

https://github.com/jruby/jruby/wiki/JRubyAndJavaCodeExamples

How to call Ruby from Java code and Java from Ruby code.

JRuby limited openssl loaded - how to eliminate?

http://stackoverflow.com/questions/9017412/jruby-limited-openssl-loaded-how-to-eliminate

Moving an Existing Rails App to run on JRuby: Install JRuby locally

https://devcenter.heroku.com/articles/moving-an-existing-rails-app-to-run-on-jruby#specify-jruby-in-your-gemfile

Best way of invoking getter by reflection

http://stackoverflow.com/questions/2638590/best-way-of-invoking-getter-by-reflection

While trying to come up with my own testing utility for stubbing/mocking, I found this. Could be a good read, but I reverted back to JMockit.

Maven: Filtering the dependency tree http://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html

Call JRuby, Jython or other JVM scripting language from Maven

http://matschaffer.com/2009/10/call-jruby-jython-from-maven/
  <executions>
    <execution>
      <id>my_script</id>
      <phase>compile</phase>
      <configuration>
        <tasks>
          <java classname="org.jruby.Main" failonerror="yes">
            <arg value="${basedir}/src/main/ruby/myscript.rb" />
          </java>
        </tasks>
      </configuration>
    </execution>
  </executions>

Guide to installing 3rd party JARs

http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
    -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

Using JRuby with Maven

https://github.com/jruby/jruby/wiki/Using-JRuby-with-Maven
    <dependency>
      <groupId>org.jruby</groupId>
      <artifactId>jruby-core</artifactId>
      <version>1.7.0.RC1</version>
    </dependency>