Categories
discuss

How to programmatically create a Java ResultSet from custom data with no database

I have some existing code that accepts a java.sql.ResultSet that contains info retrieved from an Oracle database. I would now like to reuse this code, but I’d like to pass it a ResultSet object that I create myself from some in-memory data that is not affiliated with any database. Is there an existing Java framework class that I can use for this? ResultSet has tons of methods, so implementing my own class for this seemed like overkill, even though I could ignore most of the methods for my specific case.

I was thinking of something along the lines of the old Microsoft ADO recordset object, where I could create the fields and then populate the row data for each field. This seemed like an easily googlable question, but I’ve been unable to find any good pointers.

Answer

  • Create your own AbstractResultSet class, one that (like AbstractQueue) implements all methods by throwing UnsupportedOperationException (Eclipse autogenerates these methods in a split second).
  • Now extend AbstractResultSet. The subclass can override only the methods you’re interested in implementing.
Categories
discuss

js or Jquery – obtaining viewable area of scrollable div

I currently have a a scrollable div that is populated dynamically.
I have a function that captures UpArrow and DownArrow keyPresses and changes the classes within the parent div to have one child selected at a time (basically this mimics a select input)

Here is what I want to do: I need the div’s viewable area to change (go down or up) to show the most recently “selected” child, but only if that child is not already in the viewable area of the parent.

So I need to obtain the viewable area in relation to the scrollHeight of the parent div somehow…but i am not sure how to do this…

Also, I am not sure how to set the viewable area of the parent div.

Any help would be greatly appreciated!

Answer

Doh, figured it out

First I get the viewable area via

var viewableTop = $("#parentDiv").scrollTop;
var viewableBottom = $("#parentDiv").innerHeight() + $("#parentDiv").scrollTop;

so anything between the viewableTop and viewableBottom is viewable. But really you don’t need to know that. Instead you need to know the following

//getting child position within the parent
var childPos = $("#childDiv").position().top;
//getting difference between the childs top and parents viewable area
var yDiff = ($("#childDiv").position().top + $("#childDiv").outerHeight()) - $("#parentDiv").innerHeight()

then

//if upArrow and childPosition is above viewable area (that's why it goes negative)
if(event.keyCode == 38 && childPos < 0)
    $("#parentDiv").scrollTop += childPos;//add the negative number to the scrollTop
//if downArrow and the difference between childs top and parents viewable area is greater than the height of a childDiv
else if(event.keyCode == 40 && yDiff > $("#childDiv").outerHeight()-1)
    $("#parentDiv").scrollTop += yDiff;//add the difference to the parents scrollTop
Categories
discuss

Is there an easier way to sign an XML document in Java?

I’m trying to digitally sign an XML document using Java. I’ve got an implementation working with some references I’ve found that use various implementations in the javax.xml.crypto.dsig package.

However, my current implementation is like many of the examples I’ve looked at – it’s rather verbose and involves using no less than 23 different API classes from the java.xml.crypto.dsig, javax.xml.transform, and java.security packages, among others. It feels like I’ve entered factory factory factory land, and it took me several hours just to figure out what was going on.

My question is, is there an easier way to do this? If I’ve got public/private key files and I want to add a <Signature/> to an XML document, is there a library out there that just lets me call something like:

OutputStream signFile(InputStream xmlFile, File privateKey)

…without all of the XMLSignatureFactory/CanonicalizationMethod/DOMSignContext craziness?

I’m not very well-versed in cryptography, and the Java-provided API seems rather daunting for developers like myself trying to become familiar with digital signing. If all of this is necessary or there’s currently no friendlier API out there, that’s fine and I’m willing to accept that as an answer. I’d just like to know if I’m unnecessarily taking the hard road here.

Answer

I looked at all of the options for signing XML files and decided to go with a non-standard approach. The standards were all way too verbose. Also, I didn’t need compatibility with the standards—I just needed signatures on a block of XML.

Probably the easiest way to “sign” a block of XML is to use GPG with a detached signature.

Categories
discuss

An example of encrypting an xml file in Java using bouncy castle

Can anyone show me (or provide a link to) an example of how to encrypt a file in Java using bouncy castle? I’ve looked over bouncycastle.org but cannot find any documentation of their API. Even just knowing which classes to use would be a big help for me to get started!

Answer

What type of encryption do you want to perform? Password-based (PBE), symmetric, asymmetric? Its all in how you configure the Cipher.

You shouldn’t have to use any BouncyCastle specific APIs, just the algorithms it provides. Here is an example that uses the BouncyCastle PBE cipher to encrypt a String:

import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class PBE {

    private static final String salt = "A long, but constant phrase that will be used each time as the salt.";
    private static final int iterations = 2000;
    private static final int keyLength = 256;
    private static final SecureRandom random = new SecureRandom();

    public static void main(String [] args) throws Exception {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);

        String passphrase = "The quick brown fox jumped over the lazy brown dog";
        String plaintext = "hello world";
        byte [] ciphertext = encrypt(passphrase, plaintext);
        String recoveredPlaintext = decrypt(passphrase, ciphertext);

        System.out.println(recoveredPlaintext);
    }

    private static byte [] encrypt(String passphrase, String plaintext) throws Exception {
        SecretKey key = generateKey(passphrase);

        Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
        return cipher.doFinal(plaintext.getBytes());
    }

    private static String decrypt(String passphrase, byte [] ciphertext) throws Exception {
        SecretKey key = generateKey(passphrase);

        Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
        cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
        return new String(cipher.doFinal(ciphertext));
    }

    private static SecretKey generateKey(String passphrase) throws Exception {
        PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
        return keyFactory.generateSecret(keySpec);
    }

    private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
        byte [] ivBytes = new byte[cipher.getBlockSize()];
        random.nextBytes(ivBytes);
        return new IvParameterSpec(ivBytes);
    }

}
Categories
discuss

Is is possible to bind a submit() function before any existing onsubmit/submit?

I have a form with an onsubmit attribute. I need to bind a new submit event and I need this one to be executed before any existing submit functions.

The following code demonstrates the problem.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      jQuery(function($) {
        // a plugin
        $('form').submit(function() {
          alert("Second");
        });
        // an other plugin
        $('form').submit(function() {
          alert("Third");
        });

        // this event must always be executed as first event
        $('form').submit(function() {
          alert("Always First");
        });
      });
    </script>
  </head>
  <body>
    <form onsubmit="javascript:alert('Fourth');">
      <p>
        <input type="submit">
      </p>
    </form>
  </body>
</html>

If you execute the script, first you get “Second”, then “First”.

Is is possible to bind a new submit event and specify whether the function must be called before any existing event?

Constraints:

  • Existing events must be preserved.
  • I can’t remove existing events because the content of the onsubmit attribute contains a quite complex logic written by Rails
  • (ADDED): the event should always be executed before any existing onsubmit event and already binded events (perhaps binded by an other plugin)

Any idea?

Answer

The inline submit event fires first, you could get a reference to it, nullify the onsubmit attribute on the form element, and then bind your new submit event, this one will execute your old submit handler:

  jQuery(function($) {
    var form = $('form'), oldSubmit = form[0].onsubmit;
    form[0].onsubmit = null;

    $('form').submit(function() {
      alert("First");
      oldSubmit.call(this); // preserve the context
    });
  });

Note that I use the call method to invoke your old submit handler, this is to preserve the this keyword inside that function, it will be the form element itself.

If your original onsubmit handler has some validation behavior, you can get its return value by var ret = oldSubmit.call(this);

Check the above example here.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..