Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Saturday, November 9, 2013

some points on message-level encryption

SSL and Certificates

The Most Common OpenSSL Commands

http://www.sslshopper.com/article-most-common-openssl-commands.html

Continues to be a great resources for keytool. Another similar resource exists for OpenSSL.

Southern Illinois University - File Encryption Guidelines and Procedures

http://pki.siu.edu/encrypting_files.html

basic 2-way ssl handshake

Web Help Desk Documentation Library | Installation | Importing an SSL Certificate

http://docs.webhelpdesk.com/m/5197/l/54068-importing-an-ssl-certificate

A CA Reply is the signed certificate, the result of a CA signing a certificate request (CSR).

Certificate chains may be of any length. The highest certificate in the chain, the root certificate, should be a self-signed certificate, signed by the trusted CA. Each certificate in the chain must imported into the keystore so that the complete chain can be sent to the browser. If the CA Reply does not include the chain certificates, they must be added to the keystore manually before the CA reply. The certificates must be imported in order of dependency—i.e., the root certificate must be added first, then the next chained certificate that was signed by the root certificate, and so on, down to the CA reply.

Michael Vorburger's Old Blog: Setting up two-way (mutual) SSL with Tomcat on Java5 is easy!

http://blog1.vorburger.ch/2006/08/setting-up-two-way-mutual-ssl-with.html

A pretty comprehensive tutorial on setting up 2-way SSL with Tomcat, including how to set up the keystores using keytool.

Bash

Bash Regular Expressions | Linux Journal

http://www.linuxjournal.com/content/bash-regular-expressions

Using regular expressions in bash and how to extract the match data values.

#!/bin.bash

if [[ $# -lt 2 ]]; then
    echo "Usage: $0 PATTERN STRINGS..."
    exit 1
fi
regex=$1
shift
echo "regex: $regex"
echo

while [[ $1 ]]
do
    if [[ $1 =~ $regex ]]; then
        echo "$1 matches"
        i=1
        n=${#BASH_REMATCH[*]}
        while [[ $i -lt $n ]]
        do
            echo "  capture[$i]: ${BASH_REMATCH[$i]}"
            let i++
        done
    else
        echo "$1 does not match"
    fi
    shift
done

Advanced Bash-Scripting Guide: Chapter 8.

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

Bash functions don't explicitly declare their variables. You just access $1, $2, $3, ... to access a function's parameters.

  #!/bin/bash 
  function quit {
     exit
  }  
  function e {
      echo $1 
  }  
  e Hello
  e World
  quit
  echo foo 

linux - Extract File Basename Without Path and Extension in Bash - Stack Overflow

http://stackoverflow.com/questions/2664740/extract-file-basename-without-path-and-extension-in-bash

Bash string manipulations can make easy work of parsing file names. Pretty cool!

  $ s=/the/path/foo.txt
  $ echo ${s##*/}
  foo.txt
  $ s=${s##*/}
  $ echo ${s%.txt}
  foo
  $ echo ${s%.*}
  foo

bash String Manipulations Issue 18

http://linuxgazette.net/18/bash.html

More information on bash string manipulations.

  Given:
      foo=/tmp/my.dir/filename.tar.gz 

  We can use these expressions:

  path = ${foo%/*}
      To get: /tmp/my.dir (like dirname)
  file = ${foo##*/}
      To get: filename.tar.gz (like basename)
  base = ${file%%.*}
      To get: filename 
  ext = ${file#*.}
      To get: tar.gz 

Advanced Bash-Scripting Guide: Chapter 7. Tests

http://tldp.org/LDP/abs/html/nestedifthen.html

Nested if/then condition tests.

  a=3

  if [ "$a" -gt 0 ]
  then
    if [ "$a" -lt 5 ]
    then
      echo "The value of \"a\" lies somewhere between 0 and 5."
    fi
  fi

  # Same result as:

  if [ "$a" -gt 0 ] && [ "$a" -lt 5 ]
  then
    echo "The value of \"a\" lies somewhere between 0 and 5."
  fi

Advanced Bash-Scripting Guide: Chapter 6. Tests

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html

Conditionals with variables.

  #!/bin/bash
  T1="foo"
  T2="bar"
  if [ "$T1" = "$T2" ]; then
      echo expression evaluated as true
  else
      echo expression evaluated as false
  fi

Advanced Bash-Scripting Guide: Chapter 7. Other Comparison Operators

http://www.tldp.org/LDP/abs/html/comparison-ops.html

Integer comparisons is a little different from string comparison.

-eq

    is equal to
    if [ "$a" -eq "$b" ]

-ne

    is not equal to
    if [ "$a" -ne "$b" ]

-gt

    is greater than
    if [ "$a" -gt "$b" ]

-ge

    is greater than or equal to
    if [ "$a" -ge "$b" ]

Why can't a trusted public key with certificate chain be imported into my truststore and still retain it's chain?

open https://www.java.net//node/674524 https://www.java.net//node/674524

Apparently, in order to create a public key with a certificate chain that is recognized in one's truststore, they must be associated with a private key. Since any given keystore should only have one private key, and since it is not good form to carry around someone else's private key, it seems logical that the trusted certificate entries in one's truststore (or the trusted cert entries in one's keystore) not contain trusted cert entries with full keychains.

Yeah, it is a bit unintuitive, but you cannot import certificate chains *unless* they are associated with a private key (as in the CA's reply to the CSR). Check the docs on how to import to an existing key entry (need to specify its alias).

Ivaylo

PS

There are two types of entries- key entries and trusted cert entries, and only the key entry can contain a "chain" of certificates, attached to it. The trusted cert entries are all single cert entries.

Import PKCS7 (Chained Certificate) using KeyTool command to JKS - Stack Overflow

http://stackoverflow.com/questions/15814569/import-pkcs7-chained-certificate-using-keytool-command-to-jks

keytool import or importcert can take a text file with PEM blocks or a PKCS7 file as an input file.

openssl pkcs7 -in initial_file.p7b -inform DER -print_certs -outform PEM -out certs_chain.pem

Security

More great information on message-level encryption. While the whole document is relevant only to the Web Services Stack product, there are some useful points that we can pull from the beginning of the document.

  • Message-level security is applied between the web service client and the web service itself in both directions.
  • Message-level security secures the message content itself, but it does not secure the communication channel. This is in contrast to transport-level security, where the communication channel is secured.
  • "useReqSigCert" is a special fictional encryption user that is recognized by the security module. In this case, your certificate (that is used to verify your signature) is used for the encryption of the response. Thus, it is possible to have only one configured encryption user for all clients that access the service.
  • Message-level security allows you to digitally sign or encrypt documents exchanged between systems or business partners. It improves communication-level security by adding security features that are particularly important for inter-enterprise communication. Message-level security is recommended and sometimes a prerequisite for inter-enterprise communication.
  • A digital signature authenticates the business partner signing the message and ensures data integrity of the business document carried by a message.
  • Signatures are used in two scenarios:
  • Non-repudiation of origin
  • The sender signs a message so that the receiver can prove that the sender actually sent the message.
  • Non-repudiation of receipt
  • The receiver signs a receipt message back to the sender so that the original sender can prove that the receiver actually received the original message.
  • Message-level encryption is required if message content needs to be confidential not only on the communication lines but also in intermediate message stores.

Message-level security relies on public and private x.509 certificates maintained in the J2EE keystore, where each certificate is identified by its alias name and the keystore view where it is stored. Certificates are used in the following situations:

  • When signing a message, the sender signs it with its private key and attaches its certificate containing the public key to the message.
  • The receiver then verifies the digital signature of the message with the sender’s certificate attached to the message. There are two alternative trust models to verify the authenticity of the sender’s public certificate:
  • In the direct trust model, the signer’s public key certificate is compared with the locally maintained, expected public key certificate of the partner. Therefore, the direct trust model requires offline exchange of public key certificates, which can be self-signed or issued by a CA..
  • In the hierarchical trust model, the signer’s public key certificate is validated by a locally maintained public certificate of the CA that issued the signer’s public certificate. In addition, the subject name and the issuer of the signer’s certificate is compared with the expected partner’s identity configured in a receiver agreement on the receiver side.
  • Generally, the hierarchical trust model enables chains of certificates attached to the message. The certificate used for signing has to be signed by a root CA.
  • In the hierarchical trust model, the sender and the receiver only need to agree upon the CA and the subject name that the sender has used in its certificate.
  • When encrypting a message, the sender encrypts with the public key of the receiver (also verifying the correctness of the receiver’s certificate by using the public key of the certificate’s root CA).
  • The receiver decrypts with its private key certificate.

A practical description of essential PKI concepts is provided in " What is PKI?" by Entrust. Here is a summary of some concepts:

  • Public & Private Keys – Public and private keys are complementary: public keys are used for encryption, and private keys are used for message decryption. The public key goes through a provisioning process and is provided to the "public" as an X.509 certificate. An X.509 certificate carries with it detailed information about the certificate owner (for example, name and e-mail address) and additional information about the certificate authority (CA) used to vouch for the validity and integrity of the public key contained in the X.509 certificate. The private key never leaves the enterprise and is the "crown jewel" of the security infrastructure.
  • Trusting an X.509 certificate – Whenever an X.509 certificate is presented, the receiver has to establish that the X.509 is trusted. This trust is established by certificate chain traversal, a mechanism where the X.509 receiver verifies that the issuing authority (certificate authority) indeed issued the X.509 certificate presented. An additional check required by the receiver is to check whether the X.509 certificate has been revoked. This check is accomplished by looking up the X.509's serial number in a list of revoked certificates stored in a Certificate Revocation List (CRL). You may chose not to use an issuing certificate authority (CA) and use self-signed certificates. Such certificates have to be registered with the receiver as trusted certificates that do not require certificate chain validation.
  • JKS – Java Key Store is a portable repository of X.509 certificates and private keys; it is used by Java-based applications for cryptographic operations.

Message-level security is the cornerstone of enterprise-class SOA. Using SOAP encryption and SOAP signatures, confidentiality and integrity remain "always on" by being independent of transport protocols. With security now living within the SOAP messages, it does not matter if the transport pipe – HTTP, FTP, JMS – between Web service consumers, producers, or intermediaries is SSL enabled.

Message-level security provisions have the following additional advantages when compared with transport-level security alone:

  • Granular Security – message-level encryption on any selected part of the SOAP message.
  • Always on Security – SSL security features last as long as the SSL session is established. With message-level security, SOAP messages at rest can be encrypted even after the SSL connections are terminated. Security now lives within the message and is independent of the transport.

Vim

reformat in vim for a nice column layout - Stack Overflow

http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

The 'column' command is actually a Bash command that we are pulling into the current document in our vim session.

:%!column -t -s ','

Ruby

Ruby Java Bridge

Apparently provides an API for Ruby to execute java code.

Wednesday, November 6, 2013

fun with bash scripts

escaping - Command to escape a string in bash - Stack Overflow

http://stackoverflow.com/questions/2854655/command-to-escape-a-string-in-bash
div[style='display: none;']
ul>li*>a[href=$#]{$#}; li*>a[href=$#]{$#}

Especially when printing or creating strings using user arguments to a bash script, special characters or even spaces may be introduced. We don't want a string argument to be split up into several arguments, so those values need to be escaped.

$ printf "%q" "hello\world"
hello\\world

linux - eval command in Bash and its typical uses - Stack Overflow

http://stackoverflow.com/questions/11065077/eval-command-in-bash-and-its-typical-uses

There is a way of saying 'the value of the variable whose name is in this variable'

echo ${!n}
one

Always put double quotes around variable and command substitutions, unless you know you need to leave them off. - Gilles

http://stackoverflow.com/questions/11065077/eval-command-in-bash-and-its-typical-uses

newline - Echo new line in bash prints literal \n - Stack Overflow

http://stackoverflow.com/questions/8467424/echo-new-line-in-bash-prints-literal-n

When desiring to display the name of the script file being run, even when the extra '.' is included out front...

$ ./s
$0 is: ./s
$BASH_SOURCE is: ./s
$ . ./s
$0 is: bash
$BASH_SOURCE is: ./s

Why should eval be avoided in bash, and what should I use instead? - Stack Overflow

http://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead

Using eval does smell dangerous. This might be a good read.

2.4 How to Add Files to Existing Archives

http://www.apl.jhu.edu/Misc/Unix-info/tar/tar_28.html

Came across the need to add a file to a tar archive. Doesn't seem to be in the quick help; perhaps the man pages do.

tar --append --file=afiles.tar arbalest

linux - Any way to exit bash script, but not quitting the terminal - Stack Overflow

http://stackoverflow.com/questions/9640660/any-way-to-exit-bash-script-but-not-quitting-the-terminal

I was using exit to stop all processing and not continue. It worked alright, but it would always kill my terminal session.

Instead of using exit, you will want to use return.

Dominik Honnef, http://stackoverflow.com/questions/9640660/any-way-to-exit-bash-script-but-not-quitting-the-terminal

Thursday, October 3, 2013

Illegal key size and JCE

android - java.security.InvalidKeyException: Illegal key size - Stack Overflow

Java publishes the "JCE Unlimited Strength Jurisdiction Policy Files" separate from it's normal distribution so that laws around cryptography are not violated. In order to get past this error, you must update local_policy.jar and US_export_policy.jar as indicated in the installation instructions (which come packaged with the download). One place you can download these is from Oracle.

  • local_policy.jar
  • US_export_policy.jar

maven 2 - Can I change the alias of my key? - Stack Overflow

Want to change the alias for a trusted public key or private key entry? Easy, peasy.

keytool -changealias -alias "your-very-very-long-alias" -destalias "new-alias" -keypass keypass -keystore /path/to/keystore -storepass storepass

iOS 7 iMessages and Facetime won't activate! - MacRumors Forums

http://forums.macrumors.com/showthread.php?t=1594713

I was experiencing some problems on my iMac with getting iMessages to be active. I applied updates and restarted the computer and I was back in business.

Apparently other people have had problems, especially with iOS 7.

My Apple ID

https://iforgot.apple.com/password/verify/appleid?app_type=ext&app_id=1581

Hey; it's hard remembering all those passwords all the time, right?

Bash-Prog-Intro-HOWTO-8: Functions

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

Bash functions.

   #!/bin/bash 
   function quit {
       exit
   }
   function hello {
       echo Hello!
   }
   hello
   quit
   echo foo 

Saturday, September 28, 2013

weblog; Apache CXF; getting message-level encryption to work

Bash

Bash Arrays | Linux Journal

http://www.linuxjournal.com/content/bash-arrays

Provide a list in open/close parentheses, unadorned.

array=(one two three four [5]=five)

echo "Array size: ${#array[*]}"

echo "Array items:"
for item in ${array[*]}
do
    printf "   %s\n" $item
done

Bash For Loop Examples

http://www.cyberciti.biz/faq/bash-for-loop/

The array here doesn't use parentheses.

for VARIABLE in 1 2 3 4 5 .. N
do
 command1
 command2
 commandN
done

bash - escaping newlines in sed replacement string - Stack Overflow

http://stackoverflow.com/questions/8991275/escaping-newlines-in-sed-replacement-string

Newlines will be recognized in the replace clause (the second half), but not in the match clause. Instead, you will need to use the N and D flags.

echo 'abc' | sed 's/b/\ 
> /'
a
c

Gather dependencies from pom files

http://www.grymoire.com/Unix/Sed.html#uh-51

Navigate to the root directory of Maven project with sub-modules, copy and paste the following code. The code depends on the correct order of a dependency declaration: groupId, articleId, version. Otherwise, all bets are off. This is intended to be quick and dirty; a SAX parser would be more robust.

The following temp files are used for each pom.xml in turn.

  • work.txt: contains ''
  • work2.txt: strips off '', leaving groupId:articleId:version

results.txt: The final file, providing a compilation of dependencies for all pom.xml files.

for file in $(find . -name "pom.xml")
do

cfile=$(printf '%q' $file)

sed '
# look for a <groupId>...</groupId>
/[^<]*<groupId>\([^<]*\)<\/groupId>.*$/ {
# Found one - now read in the next line
 N
# delete the <groupId>...</groupId> and replace with <maven-dependency>
 s/[^<]*<groupId>\([^<]*\)<\/groupId>[\n\r]*[^<]*/<maven-dependency>\1/
}

/<artifactId>\([^<]*\)<\/artifactId>.*$/ {
 N
 s/<artifactId>\([^<]*\)<\/artifactId>[\n\r]*[^<]*/:\1/
}

s/<version>\([^<]*\)<\/version>.*/:\1<\/maven-dependency>/

' $file > work.txt

echo -e "\n${cfile}\n===========================================" > work2.txt

cat work.txt | grep "<maven-dependency>[^<]*<\/maven-dependency>" | sed "s/<maven-dependency>\([^<]*\)<\/maven-dependency>/\1/" >> work2.txt; cat work2.txt

cat work2.txt >> results.txt

done

Along the same lines, there is also a little Ruby script for extracting out the articleId from the groupId:articleId:version:

#[Extract dependency name (Ruby)]

#E.g., 
dependencies = %w[
edu.ucmerced.ucpath.idm:ucm-ucpath-idm:0.0.2-SNAPSHOT
it.svario.xpathapi:xpathapi-jaxp:RELEASE
org.eclipse.m2e:lifecycle-mapping:1.0.0
org.apache.maven.plugins:maven-install-plugin:2.4
com.google.code.maven-replacer-plugin:replacer:1.5.2
org.codehaus.mojo:properties-maven-plugin:1.0-alpha-2
org.apache.maven.plugins:maven-install-plugin:2.4
com.google.code.maven-replacer-plugin:replacer:1.5.2
]

puts dependencies.map{|x| first = x.index(/:/); x.slice(first+1, x.index(/:/, first+1) - first-1)}

How to reference a variable within sed? - The UNIX and Linux Forums

http://www.unix.com/shell-programming-scripting/39175-how-reference-variable-within-sed.html
tmp="abcdefg"
sed "s/${tmp}/good"

Replace the single quotes with double quotes. Single quotes prevent variable expansion.

http://www.unix.com/shell-programming-scripting/39175-how-reference-variable-within-sed.html

escape string in bash script so it can be used in command line

http://www.linuxquestions.org/questions/linux-software-2/escape-string-in-bash-script-so-it-can-be-used-in-command-line-360664/

Use double quotes.

You don't need to escape a string if you quote it - say you want to pass all the arguments to ls, instead of

ls $*

write

ls "$*"

Java; web services

Web Service Definition Language (WSDL)

http://www.w3.org/TR/wsdl#_soap:address

What purpose does soap:address serve? It appears to be the actual endpoint.

<definitions .... >
    <port .... >
        <binding .... >
           <soap:address location="uri"/> 
        </binding>
    </port>
</definitions>
? Apache CXF -- WS-SecurityPolicy http://cxf.apache.org/docs/ws-securitypolicy.html

Configuration for message-level encryption can be easily accomplished. The following server and client configurations should be loaded either in the Server/Client Java class or in the pom.xml configuration

Java Class

  SpringBusFactory bf = new SpringBusFactory();
  URL busFile = new ClassPathResource("wssec-server.xml").getURL();
  Bus bus = bf.createBus(busFile.toString());
  BusFactory.setDefaultBus(bus);

pom.xml

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <executions>
        <execution>
            <phase>test</phase>
            <goals>
                <goal>java</goal>
            </goals>
            <configuration>
                <mainClass>edu.ucmerced.ucpath.idm.Runner</mainClass>
                <arguments>
                    <argument>../ws-ora-idm-wsdl/src/main/resources/wsdl/IDMServices/IDMServices.wsdl</argument>
                </arguments>
                <systemProperties>
                  <systemProperty>
                    <key>cxf.config.file</key>
                    <value>cxf-client.xml</value>     
                  </systemProperty>
                </systemProperties>
            </configuration>
        </execution>
    </executions>
</plugin>

Server

    <jaxws:endpoint id="server"
      implementor="demo.wssec.server.GreeterImpl"
      endpointName="s:SoapPort"
      serviceName="s:SOAPService"
      address="http://localhost:9001/SoapContext/SoapPort"
      wsdlLocation="wsdl/hello_world.wsdl"
      xmlns:s="http://apache.org/hello_world_soap_http">
        
      <jaxws:properties>
         <entry key="ws-security.signature.properties" value="serviceKeystore.properties"/>
         <entry key="ws-security.signature.username" value="myservicekey"/>

         <entry key="ws-security.callback-handler" 
                value="demo.wssec.server.ServerCallbackHandler"/>

         <entry key="ws-security.encryption.properties" value="serviceKeystore.properties"/>
         <entry key="ws-security.encryption.username" value="myclientkey"/>
      </jaxws:properties> 
    </jaxws:endpoint>

Client

    <jaxws:client name="{http://apache.org/hello_world_soap_http}SoapPort" createdFromAPI="true">
       <jaxws:properties>
           <entry key="ws-security.signature.properties" value="clientKeystore.properties"/>
           <entry key="ws-security.signature.username" value="myclientkey"/>
           <entry key="ws-security.callback-handler" 
                  value="demo.wssec.client.ClientCallbackHandler"/>
           <entry key="ws-security.encryption.properties" value="clientKeystore.properties"/> 
           <entry key="ws-security.encryption.username" value="myservicekey"/>
       </jaxws:properties>
   </jaxws:client>

Propery files should include location of certificates and keystore password. The private key password cannot be provided here, but should use the callback to provide the correct private key.

Properties

org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.type=jks
org.apache.ws.security.crypto.merlin.keystore.password=sspass
org.apache.ws.security.crypto.merlin.keystore.alias=myservicekey
org.apache.ws.security.crypto.merlin.keystore.file=keys/servicestore.jks

Java callback-handler

public void handle(Callback[] callbacks) throws IOException,
        UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof WSPasswordCallback) {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
            if ("myservicekey".equals(pc.getIdentifier())) {
                pc.setPassword("skpass");
                break;
            }
        }
    }
}

See https://github.com/dcvezzani/mustached-batman for a complete example.

Maven Repository: org.apache.ws.security » wss4j

» 1.5.6 http://mvnrepository.com/artifact/org.apache.ws.security/wss4j/1.5.6

Pom.xml dependency entry.

<dependency>
 <groupId>org.apache.ws.security</groupId>
 <artifactId>wss4j</artifactId>
 <version>1.5.6</version>
</dependency>

WS-SecurityPolicy 1.2

http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/ws-securitypolicy-1.2-spec-os.html

Documentation of the nodes in the WS-SecuirtyPolicy namespace.

XML Namespace Document for WS-Security-Policy 1.3

http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200802

Documentation of the nodes in the WS-SecuirtyPolicy namespace.

Re: Eclipse, CXF and WS-SecurityPolicy

http://mail-archives.apache.org/mod_mbox/cxf-users/201307.mbox/%3CF172D30F-6747-44B2-A4CE-7EFBD7710DEA@indivica.com%3E

An error like what follows indicates that possibly the wrong namespace is being specified or the namespace is missing altogether.

> Jul 27, 2013 12:41:56 AM org.apache.cxf.ws.policy.AssertionBuilderRegistryImpl handleNoRegisteredBuilder
> WARNING: No assertion builder for type {http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}RequiredParts registered.

Maven Repository: org.apache.cxf » cxf-rt-ws-security

» 2.4.1 http://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-ws-security/2.4.1

Entry description

<dependency>
 <groupId>org.apache.cxf</groupId>
 <artifactId>cxf-rt-ws-security</artifactId>
 <version>2.4.1</version>
</dependency>

Java web services: WS-Security with CXF

http://www.ibm.com/developerworks/library/j-jws13/

Walk-through for creating a web service, using WS-Security with the Apache CXF web services stack

X.509 Certificates

X.509 - Wikipedia, the free encyclopedia

http://en.wikipedia.org/wiki/X.509

Was researching what exactly the significance is of signed certificates.

As far as I can tell, most of the time it's only purpose is to validate a trusted public key.

The Most Common Java Keytool Keystore Commands

http://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

A great resource common keytool commands.

Thursday, September 12, 2013

weblog; saving my neck with git-reflog and namespace conflicts

Bash

bash - how to represent multiple conditions in shell script? - Stack Overflow

http://stackoverflow.com/questions/3826425/how-to-represent-multiple-conditions-in-shell-script
if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]

Only process the file entries with 'webapp-idm' and 'webapp' in their name.

if [[ ( $cp =~ "webapp-idm" ) || ( $cp =~ "webapp" ) ]]
then
echo "processing $cp"
fi

bash - how to loop list of file names returned by find - Stack Overflow

http://stackoverflow.com/questions/9612090/how-to-loop-list-of-file-names-returned-by-find
for i in $(find -name \*.iso); do
    process "$i"
done

Loop for all .classpath files found recursively from the current directory.

for cp in $(find . -name ".classpath")
do
echo $cp
done

Other Comparison Operators

http://tldp.org/LDP/abs/html/comparison-ops.html
-eq

    is equal to

    if [ "$a" -eq "$b" ]

regex - use regular expression in if-condition in bash - Stack Overflow

http://stackoverflow.com/questions/2348379/use-regular-expression-in-if-condition-in-bash
$ for file in *; do [[ $file =~ "..g" ]] && echo $file ; done
abg
degree
..g

Java

XmlType (Java EE 5 SDK)

http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlType.html#name%28%29

When processing WSDLs and XSDs to generate Java code, node name clashes could be a problem.

Git

git ready » reflog, your safety net

http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html http://stackoverflow.com/questions/4786972/list-of-all-git-commits
git reflog

Pack up / clean up your repository (beware!)

# git reflog expire --expire=1.minute refs/heads/master
# git fsck --unreachable      
# git prune                   
# git gc                      

...you can use it as a safety net: you shouldn’t be worried that a merge, rebase, or some other action will destroy your work since you can find it again using this command.

http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html

Tuesday, September 10, 2013

weblog; bash, sed

Bash: creating scripts for cleaning up documentation files

bash script: get just filename from path

http://stackoverflow.com/questions/3362920/bash-script-get-just-filename-from-path
a=/tmp/file.txt
b=$(basename $a)
echo $b

<a href="file.txt" target="_new">file.txt</a>

Used this to extract the filename only from the path. I'm storing files that haven't been processed yet in 'unprocessed'.

#[command line]
find unprocessed -maxdepth 1 -type f -name "[^.]*" | xargs bin/convert_rails_html_to_dev_docs.sh


#[bin/convert_rails_html_to_dev_docs.sh]
for xpathfile in $@
do

xfile=$(basename $xpathfile)
<div class="notes">
  <p>.</p>
</div>

done

xargs: How To Control and Use Command Line Arguments; {} as the argument list marker

http://www.cyberciti.biz/faq/linux-unix-bsd-xargs-construct-argument-lists-utility/
find . -name "*.bak" -print0 | xargs -0 -I {} mv {} ~/old.files

-0 -I {} is especially important; I still need to find out what it means though. -I {} indicates what the replacement symbol is.

escaping newlines in sed replacement string

http://stackoverflow.com/questions/8991275/escaping-newlines-in-sed-replacement-string
[jaypal:~/Temp] echo 'abc' | sed 's/b/\ 
> /'

At first, I tried to enter a ^M () at the point I desired a new line. After reading this SO I decided to try simply putting in a straight-out carriage return and it worked! Like the SO says, you still need to escape the carriage return.

sed 's_.* name="csrf-token" />$_<link href="assets/application.css?body=1" media="all" rel="stylesheet" type="text/css" />\
<script src="assets/application.js?body=1" type="text/javascript"></script>_' $xfile.tmp > work/$xfile

Bash For Loop Examples

http://www.cyberciti.biz/faq/bash-for-loop/
for VARIABLE in file1 file2 file3
do
 command1 on $VARIABLE
 command2
 commandN
done

Or to get all arguments that may have been provided as arguments to the script when it was run (e.g., when using xargs)

for VARIABLE in $@
do
 command1 on $VARIABLE
 command2
 commandN
done

How to read command line arguments in a bash script

http://how-to.wikia.com/wiki/How_to_read_command_line_arguments_in_a_bash_script
command: ./script.bash alpha beta gamma
Variables: $1=='alpha'; $2=='beta'; $3=='gamma' 

using a user defined bash function in xargs [duplicate]

http://stackoverflow.com/questions/11232782/using-a-user-defined-bash-function-in-xargs

I decided to create an actual bash script to funnel xargs to.

find unprocessed -maxdepth 1 -type f -name "[^.]*" | xargs bin/convert_rails_html_to_dev_docs.sh
find work -maxdepth 1 -type f -name "[^.]*" | xargs bin/install_work_files.sh

Recursively list non-Hidden Files

http://ubuntuforums.org/archive/index.php/t-931966.html
find /path -type d -name "[^.]*"

When you need to exclude file entries from your list. This leaves out any .*.swp files that might be hanging around.

find work -maxdepth 1 -type f -name "[^.]*" | xargs bin/install_work_files.sh

Here's another way using ls, although I wasn't able to get it working.

Bash: How list only the files?

http://stackoverflow.com/questions/10574794/bash-how-list-only-the-files
find . -maxdepth 1 -type f

Listing just the file entries (without any directories).

find work -maxdepth 1 -type f

Find all file entries under the work directory.

How do I tell if a file does not exist in bash?

http://stackoverflow.com/questions/638975/how-do-i-tell-if-a-file-does-not-exist-in-bash
if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

I used this to determine whether I needed to create a directory or not. My script exited when the directory already existed and I attempted to create it again.

if [ ! -e "unprocessed" ]
then
  mkdir unprocessed
fi

Advanced Bash-Scripting Guide: File test operators

http://tldp.org/LDP/abs/html/fto.html
-e       file exists

Of course, there are many other options listed in this resource besides this one. This is just the one I was looking for.

Passing parameters to a bash function

http://stackoverflow.com/questions/6212219/passing-parameters-to-a-bash-function
function_name () {
   command...
} 

This is how to create a bash function. I was going to use this, but finally gave up and decided to use a shell script instead.

Sed - An Introduction and Tutorial by Bruce Barnett: Using \1 to keep part of the pattern

http://www.grymoire.com/Unix/Sed.html#uh-0
sed 's/\([a-z]*\).*/\1/'

This looks quite comprehesive. As the author says, I fall into the category of those not really knowing how to use sed. I've started my journey :)

Anyhow, sed is a marvelous utility. Unfortunately, most people never learn its real power. The language is very simple, but the documentation is terrible.

http://www.grymoire.com/Unix/Sed.html#uh-0

Friday, August 2, 2013

Work notes; unit testing and vim

Redactor

Installing comfortable mexican sofa

https://github.com/comfy/comfortable-mexican-sofa

Rails generator and haml?! I want ERB please!

mvim ~/.rvm/gems/ruby-1.9.3-p194@rails328/gems/comfortable_mexican_sofa-1.8.4/lib/comfortable_mexican_sofa/engine.rb

# comment out 'haml-rails'
# require 'haml-rails'

Of course, when your done generating new code, you will need to enable it again or comfy won't work right.

Integrate a different wysiwyg tool for content editing.

https://github.com/comfy/comfortable-mexican-sofa/issues/321 https://github.com/comfy/comfortable-mexican-sofa/wiki/Replacing-default-wysiwyg-editor-with-redactor

Not ckeditor, but it should be very similar to this: https://github.com/comfy/comfortable-mexican-sofa/wiki/Replacing-default-wysiwyg-editor-with-redactor

https://github.com/comfy/comfortable-mexican-sofa/issues/321

Uploading images

http://imperavi.com/redactor/docs/images/ http://guides.rubyonrails.org/form_helpers.html

Vim

Save replace value in vim

let @y = ''

let @z = '/<pre [^>]\+\+><return>'
let @z .= 'v/><return>'
let @z .= '"yy'

normal @z
http://superuser.com/questions/575831/save-replace-value-in-vim

Clear out @y register. Search for desired string, start selecting until specified pattern, and while selection is active, shove it in the @y register ("Yy would append to the @y register).

Formatting columns in a selected block

:%!column -t

"in visual mode
:!column -t

" establish columns by splitting on Tab character
" Ctrl-V, Tab to generate '^I'
:%!column -t -s "^I"
http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

Because my files didn't have a space I had to use :%!column -t -s ','. It removes the commas, so they're not technicaly csv files anymore. But arranges them beautifully, which is what I needed.

http://stackoverflow.com/questions/1229900/reformat-in-vim-for-a-nice-column-layout

To format only the content of the visual block, delimit on :

:!column -t -s '<tab>'

Works like a champ.

Using marks

   ma     set mark a at current cursor location
  'a      jump to line of mark a (first non-blank character in line)
  `a      jump to position (line and column) of mark a 
  :marks  list all the current marks 
http://vim.wikia.com/wiki/Using_marks

Substitute with contents of register or lines range from elsewhere in file in Vim

:%s/foo/\=@a/g
http://stackoverflow.com/questions/662734/substitute-with-contents-of-register-or-lines-range-from-elsewhere-in-file-in-vi

No other replacement values can be included with '\=@a'. Otherwise, it won't work.

Vim - if/elseif/else statements in for loop (command mode)

:for i in range(1,10) | if i > 5 | put =i | endif | endfor
http://stackoverflow.com/questions/6544903/vim-if-elseif-else-statements-in-for-loop-command-mode

Get statement on a single line

While Loops

while c <= 4
  let total += c
  let c += 1
endwhile
http://learnvimscriptthehardway.stevelosh.com/chapters/36.html

Simple enough.

Cool things to do with substitutions

http://vim.wikia.com/wiki/Search_and_replace

How to concatenate

let s .= '%' . i . 'T'
http://stackoverflow.com/questions/4911692/what-does-in-vim-scripts-mean

Like Bash, the spaces are crucially important. Items must be separated by a space on either side.

Wonderful and comprehensive resource!

Other ways to substitute

http://stackoverflow.com/questions/2156405/how-do-i-do-a-g-with-a-concatenating-of-submatches-in-vim

Appending to a register using the capital version of the register letter

    "Kyy
http://stackoverflow.com/questions/1497958/how-to-use-vim-registers

Wow! This stuff is cryptic.

What is 'f' and 'F' and how do they work?

F)vi(
http://learnvimscriptthehardway.stevelosh.com/chapters/15.html

:normal! is something we'll talk about in a later chapter, but for now it's enough to know that it is a command used to simulate pressing keys in normal mode. For example, running :normal! dddd will delete two lines, just like pressing dddd. The at the end of the mapping is what executes the :normal! command.

http://learnvimscriptthehardway.stevelosh.com/chapters/15.html

(f)ind character; (f)next, (F)previous

(vi)select block body delimited by '()', '{}', '<>', or '[]'

Escaping single quotes is easy, but a little verbose

"'" . x . "'"
http://vim.1045645.n5.nabble.com/escape-and-td1200763.html

Remember, the spaces between concatenated strings is important!

Search only over a visual range

/\%Vpattern

<div>hello</div>
http://vim.wikia.com/wiki/Search_only_over_a_visual_range

This saved my skin; the trick is to create a highlighted range, escape, and then use the substitution flag '\%V' to limit substitution to the last selected block. When including a '^' before the flag, it means the first in the selection, not each line in the selection. Interesting...

Getting zen-code to format snippet using multi-line

    let @z = 'gvj<escape>A<return><return><escape>gv<c-y>,div.notes>p*<return>'

A little difficult to see from code snippet, but add a line to the currently selected block, add a couple of new lines after the block, select the last selected block again and then execute the zen-code command.

Ruby; Rails

Error, Ruby on Rails: Encoding::UndefinedConversionError in CoursesController#attachment “\xFF” from ASCII-8BIT to UTF-8

  ...
  File.open(Rails.root.join('public', 'upload', uploaded_io.original_filename), 'wb') do |file|
    file.write(uploaded_io.read)
  end
http://stackoverflow.com/questions/13909812/error-ruby-on-rails-encodingundefinedconversionerror-in-coursescontrollerat

Try to open the file in binary mode ('wb' instead of 'w')

http://stackoverflow.com/questions/13909812/error-ruby-on-rails-encodingundefinedconversionerror-in-coursescontrollerat

Uploading files

<%= form_for @person do |f| %>
  <%= f.file_field :picture %>
<% end %>
http://guides.rubyonrails.org/form_helpers.html

Html

Pure CSS Blockquote Styling

<blockquote>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae!
<cite>Somebody famous</cite>
</blockquote>
http://www.webmaster-source.com/2012/04/24/pure-css-blockquote-styling/

I'm trying to use this to format quotes in my blog.

Twitter Bootstrap reference (for v2.3.2)

    <div class="row">
    <div class="span4">...</div>
    <div class="span8">...</div>
    </div>
http://getbootstrap.com/2.3.2/scaffolding.html

The new version has some rather significant changes.

CMS

Allow use of ERB in cms

https://github.com/comfy/comfortable-mexican-sofa/issues/67

I have fixed the initializer changing disable_irb=true to allow_irb=false to match the Configuration class definition. My fork is at https://github.com/dsapala/comfortable-mexican-sofa . Feel free to pull commit 6706ff2 for that change.

https://github.com/comfy/comfortable-mexican-sofa/issues/67

Java; Unit Test Mocking

Maven setup for the Mockito API with JUnit

<properties>
    <powermock.version>1.5.1</powermock.version>
</properties>
<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4-legacy</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
</dependencies>
http://code.google.com/p/powermock/wiki/Mockito_maven

I'm beginning to concede that Mockito is the option most similar to Ruby style mocking.

mockito mock a constructor with parameter

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}
http://stackoverflow.com/questions/13364406/mockito-mock-a-constructor-with-parameter

Mocking constructors requires something extra from just Mockito.

Mocking Static Method

   @PrepareForTest(Static.class); // Static.class contains static methods
        PowerMockito.mockStatic(Static.class);   
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
http://code.google.com/p/powermock/wiki/MockitoUsage

how do I mock Class myVar in Mockito (or PowerMock if needed)?

class FooBar {
  static class Factory {
    static FooBar instance;
    FooBar getInstance() {
      if (instance == null) {
        instance = new FooBar();
      }
      return instance;
    }
  }
  // ...
}
http://stackoverflow.com/questions/13057933/how-do-i-mock-class-extends-list-myvar-in-mockito-or-powermock-if-needed

Mockito is designed exclusively for mocking instances of objects. Under the hood, the mock method actually creates a proxy that receives calls to all non-final methods, and logs and stubs those calls as needed. There's no good way to use Mockito to replace a function on the Class object itself.

http://stackoverflow.com/questions/13057933/how-do-i-mock-class-extends-list-myvar-in-mockito-or-powermock-if-needed

Maven configuration for using PowerMockito?

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CC8QFjAA&url=http%3A%2F%2Fmvnrepository.com%2Fartifact%2Forg.powermock&ei=PyT8UfTwL8HKiAKxmYHICQ&usg=AFQjCNHKogX9smNHkXFJn6B7xxvH2SHKOA&sig2=8Sn64TLEqcyaFNVx_Lua8w&bvm=bv.50165853,d.cGE

It appears the site was down when I tried to capture data into my blog entry.

Mockito documentation (1.6)

 //Let's import Mockito statically so that the code looks clearer
 import static org.mockito.Mockito.*;
 
 //mock creation
 List mockedList = mock(List.class);
 
 //using mock object
 mockedList.add("one");
 mockedList.clear();
 
 //verification
 verify(mockedList).add("one");
 verify(mockedList).clear();
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html

It appears this has a little guide of common uses for Mockito.

Mockito matchers

  //stubbing using anyInt() argument matcher
  when(mockedList.get(anyInt())).thenReturn("element");
  
  //following prints "element"
  System.out.println(mockedList.get(999));
  
  //you can also verify using argument matcher
  verify(mockedList).get(anyInt());
http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Matchers.html

Testing with Mockito - Tutorial

http://www.vogella.com/articles/Mockito/article.html

Fruzenshtein's notes on JUnit and Mockito

    ...  
        @Mock  
        IContainer coffeeContainer;  
        @Mock  
        IContainer waterContainer;  
    ...  
http://fruzenshtein.com/junit-and-mockito/

Mockito - 2 minute tutorial

public class CustomiizeMethodBehaviour  
{  
    public static void main(String[] args)  
    {  
        List myMockedList = mock(List.class);   
        when(myMockedList .get(0)).thenReturn("target");  
          
        System.out.println(myMockedList .get(0));  
    }  
}  
http://www.2min2code.com/articles/mockito_intro/stubbing_method_hardcoded

Mockito documentation (1.9.5)

http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#1

Obviously, more comprehensive than the 1.6 version.

JRuby Array to Java Array

{"options"=>["Option One", "Option Two"]}["options"].to_java :string

[1, 2, 3].to_java(:int)
http://stackoverflow.com/questions/1532606/jruby-array-to-java-array

Taming the beast: Using JRuby and RSpec to test a J2EE application

require 'java'
include_class 'org.springframework.context.ApplicationContext'
include_class
  'org.springframework.context.support.ClassPathXmlApplicationContext'
describe "Calculator" do
  it "should add numbers correctly" do
    application_context =
      ClassPathXmlApplicationContext.new "ApplicationContext.xml"
    calculator =  application_context.getBean "calculatorService"
    calculator.sum([1, 2]).should == 3
    calculator.sum([2, 2]).should == 4
    calculator.sum([2, 3, 4]).should == 9
  end
end
http://patshaughnessy.net/2009/6/25/taming-the-beast-using-jruby-and-rspec-to-test-a-j2ee-application

Working with J2EE applications is something like wandering in a jungle: you never quite know what wild animal you’ll find around the next corner... whatever it is, you’re guaranteed to spend countless hours wasting time learning things you really didn’t want to know.

[Let me] show how you can get your J2EE application under control by using JRuby and RSpec.

http://patshaughnessy.net/2009/6/25/taming-the-beast-using-jruby-and-rspec-to-test-a-j2ee-application

Mock File class and NullPointerException

java.lang.NullPointerException at java.io.File.(File.java:308)

File folder = Mockito.mock(File.class);
when(folder.getPath()).thenReturn("C:\temp\");
File file = new Agent().createNewFile(folder, "fileName");
http://stackoverflow.com/questions/3515011/mock-file-class-and-nullpointerexception/3515129#3515129

RSpec, JRuby, Mocking, and Multiple Interfaces

http://blog.nicksieger.com/articles/2006/12/01/rspec-jruby-mocking-and-multiple-interfaces/

The prospect of doing behavior-driven development in Java has just taken a step closer with the news of RSpec running on JRuby. This is already a big step that will have an impact on Ruby and Java programmers alike in a number of ways."

http://blog.nicksieger.com/articles/2006/12/01/rspec-jruby-mocking-and-multiple-interfaces/
he prospect of doing behavior-driven development in Java has just taken a step closer with the news of RSpec running on JRuby. This is already a big step that will have an impact on Ruby and Java programmers alike in a number of ways."

The RMock 2.0.0 user guide

http://rmock.sourceforge.net/documentation/xdoc.html

JRuby for the Win

http://winstonyw.com/assets/downloads/JRubyForTheWin.pdf

A PDF document that contains some of the authors notes on JTestR, a product I had hoped would do the job. It appears that it fell off the table awhile back in 2009. Sad, really.

RSpec 1.3.0 Documentation; Configuration

Spec::Runner.configure do |config|
  config.mock_with :rspec, :mocha, :flexmock, or :rr
end
http://rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Runner/Configuration.html

Admittedly, this example is deprecated. See a more recent version of RSpec.

JtestR documentation; Mocking

functional_tests do
  test "that a new HashMap can be created based on another map" do
    map = Map.new

    map.expects(:size).returns(0)

    iter = Iterator.new
    iter.expects(:hasNext).returns(false)

    set = Set.new
    set.expects(:iterator).returns(iter)

    map.expects(:entrySet).returns(set)

    assert_equal 0, HashMap.new(map).size
  end
end
http://jtestr.codehaus.org/Mocks

Only problem is the mocked bindings disappear once execution enters the actual Java code :(

JtestR documentation; Getting Started

http://jtestr.codehaus.org/Getting+Started

Mocking JRuby

  require 'test/unit'
  require 'rubygems'
  require 'mocha'

  ...

    def test_filling_removes_inventory_if_in_stock
      order = OrderImpl.new(TALISKER, 50)
      warehouse = Warehouse.new
      warehouse.stubs(:hasInventory).with(TALISKER, 50).returns(true)
      warehouse.stubs(:remove).with(TALISKER, 50)

      order.fill(warehouse)
      assert order.is_filled
    end  
http://memeagora.blogspot.com/2007/10/mocking-jruby.html

Testing is one of the easy ways to sneak JRuby into your organization because it is easier to write tests in dynamic languages (especially mock object tests) and it isn't code that is deployed, so it eases the minds of the furniture police somewhat.

http://memeagora.blogspot.com/2007/10/mocking-jruby.html

Mocking core Java classes with jmockit

  import mockit.*;
  import java.math.*;

  public class Test {
    public static void main(String[] args) {
      Mockit.redefineMethods(BigDecimal.class, new BigDecimalMock());
      System.err.println(BigDecimal.ONE.add(BigDecimal.ONE));
    }
  }
http://evan.tiggerpalace.com/articles/2008/05/02/mocking-core-java-classes-with-jmockit/

So, yes, Virginia, it is possible to mock core classes... To make this work practically would likely necessitate launching a separate VM so as to 'scope' the mock to a particular test.

Fugly.

http://evan.tiggerpalace.com/articles/2008/05/02/mocking-core-java-classes-with-jmockit/

Bash

zen coding multiple elements with children

.br-title>span^.br-content>cfoutput
http://stackoverflow.com/questions/16739994/zen-coding-multiple-elements-with-children

Highlighted block is applied to the last child selector.

Java

Setting the classpath

java -classpath example

java -cp example
http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html

Java Initialize an int array in a constructor

data = new int[]{0, 0, 0};
http://stackoverflow.com/questions/8068470/java-initialize-an-int-array-in-a-constructor

Wednesday, July 24, 2013

Work notes; bash

Bash

How to view the rails console history?

less ~/.irb_history
http://stackoverflow.com/questions/11601303/how-to-view-the-rails-console-history

I opened one of my log files from finder and it was automatically opened in textedit. I proceeded to select content using vim key sequences and ended up over-writing a section. "No problem," I thought; "I'll just close the file and not save." To my dismay, textedit didn't even prompt me and saved the file just before closing it. And with no backups, I figured I had lost it.

But wait; I seem to recall that the Rails console has history because I can up-arrow to previous commands. Where is it? How relieved I was to discover '~/.irb_history'.

Exclude items in a list in a bash script

http://moinne.com/blog/ronald/bash/exclude-items-in-a-list-in-a-bash-script

Looks interesting, but I went with a different route.

Bash Shell Loop Over Set of Files

FILES="./ws-idm/src/main/config/server.jks
./ws-ucidm/src/main/config/server.jks
./ws-ucidm-service/src/main/config/server.jks"

for f in $FILES
do
 cp /Users/davidvezzani/java-app/tomcat/conf/server.002.jks $f
done
http://www.cyberciti.biz/faq/bash-loop-over-file/

I needed to update all instances of a Java keystore I was working on.

Monday, July 22, 2013

Work notes; ssl and certificates

SSL; Cipher suites

What are cipher suites?

http://en.wikipedia.org/wiki/Cipher_suite

Configuring Apache to accept a particular list of cipher suites

https://httpd.apache.org/docs/2.0/ssl/ssl_howto.html

Testing ssl connections using OpenSSL's s_client and s_server

http://wiki.wireshark.org/SSL

Bash script to test OpenSSL's supported cipher suites against a given web server

https://www.ssllabs.com/ssltest/index.html

OpenSSL's documentation for ciphers

http://www.openssl.org/docs/apps/ciphers.html#NAME

How to Disable SSL weak Ciphers in Tomcat Server

http://www.fromdev.com/2009/02/tomcat-best-practices-securing-ssl-by.html

How to control the SSL ciphers available to Tomcat

http://stackoverflow.com/questions/7417809/how-to-control-the-ssl-ciphers-available-to-tomcat

Java™ Cryptography Architecture Standard Algorithm Name Documentation; JSSE Cipher Suite Names

http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#jssenames

SSLHandshakeException: Received fatal alert: handshake_failure when setting ciphers on tomcat 7 server

http://stackoverflow.com/questions/15544116/sslhandshakeexception-received-fatal-alert-handshake-failure-when-setting-ciph?rq=1

-keyalg is only one part of the solution; the other peer involved in the ssl conversation must support a compatible hash algorith for OID in addition to supporting a common cipher suite

SSL; handshake

Give me a detailed breakdown of how the ssl-handshake works

http://pic.dhe.ibm.com/infocenter/tivihelp/v2r1/index.jsp?topic=%2Fcom.ibm.itame2.doc_5.1%2Fss7aumst18.htm

An overview of the SSL handshake

http://publib.boulder.ibm.com/infocenter/wmqv6/v6r0/index.jsp?topic=%2Fcom.ibm.mq.csqzas.doc%2Fsy10660_.htm http://pic.dhe.ibm.com/infocenter/tivihelp/v2r1/index.jsp?topic=%2Fcom.ibm.itame2.doc_5.1%2Fss7aumst18.htm

SSL; keytool

Documentation for keytool

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

Keytool and the -keyalg option

http://stackoverflow.com/questions/15544116/sslhandshakeexception-received-fatal-alert-handshake-failure-when-setting-ciph?rq=1

Java keytool; common commands

https://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

Keytool keeps giving SHA256 sigalg instead of requested alg

http://stackoverflow.com/questions/14163889/keytool-keeps-giving-sha256-sigalg-instead-of-requested-alg

keytool - Key and Certificate Management Tool; Supported Algorithms and Key Sizes

http://docs.oracle.com/javase/1.5.0/docs/tooldocs/solaris/keytool.html

How do I generate a 2048 bit CSR using Java Keytool?

http://www.entrust.net/knowledge-base/technote.cfm?tn=8425

keytool - Key and Certificate Management Tool; Option Defaults

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

SSL; misc

Online tester for SSL-enabled servers

https://www.ssllabs.com/ssltest/index.html

Hash Algorithm OIDs

http://msdn.microsoft.com/en-us/library/ff635603.aspx

SSL; OpenSSL

Creating a self-signed test certificate

http://www.openssl.org/docs/HOWTO/certificates.txt

Public Key Encryption and Digital Signatures using OpenSSL

http://sandilands.info/sgordon/public-key-encryption-and-digital-signatures-using-openssl

these procedures do not involve browsers at all; it's a great example in raw form of how to use certificates for encrypting and signing data

Testing ssl connections using OpenSSL's s_client and s_server

http://wiki.wireshark.org/SSL

Bash script to test OpenSSL's supported cipher suites against a given web server

https://www.ssllabs.com/ssltest/index.html

OpenSSL's documentation for ciphers

http://www.openssl.org/docs/apps/ciphers.html#NAME

Tomcat

How to Disable SSL weak Ciphers in Tomcat Server

http://www.fromdev.com/2009/02/tomcat-best-practices-securing-ssl-by.html

How to control the SSL ciphers available to Tomcat

http://stackoverflow.com/questions/7417809/how-to-control-the-ssl-ciphers-available-to-tomcat

Tomcat configuration; creating a certificate for an SSL-enabled Tomcat server

http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html

HOWTO: Secure SSL in Tomcat and JBoss

http://www.techstacks.com/howto/secure-ssl-in-tomcat.html

The HTTP Connector; SSL Support - BIO and NIO

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Vim

How do you do a case insensitive search using a pattern modifier using less?

http://stackoverflow.com/questions/16828/how-do-you-do-a-case-insensitive-search-using-a-pattern-modifier-using-less

How to do case insensitive search in Vim

http://stackoverflow.com/questions/2287440/how-to-do-case-insensitive-search-in-vim

Bash

Bash custom functions

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

What's the best way to check that environment variables are set in Unix shellscript

http://stackoverflow.com/questions/307503/whats-the-best-way-to-check-that-environment-variables-are-set-in-unix-shellscr

Weblogic

Using Weblogic SSL

http://www.inf.fu-berlin.de/lehre/WS00/SWT/BEA/documentation/docs51/classdocs/API_secure.html

Introduction to WebLogic Security; Cipher Suites

http://docs.oracle.com/cd/E13222_01/wls/docs81/secintro/concepts.html

Understanding WebLogic Security; J2EE and WebLogic Security

http://docs.oracle.com/cd/E11035_01/wls100/secintro/concepts.html