Extremely Serious

Category: Java (Page 3 of 4)

Java 6 to use TLS 1.2 by using BouncyCastle

  1. Download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6. (i.e. if the link is already dead then download this instead jce_policy-6.)
  2. Extract the downloaded archive and follow the installation procedure found in the README.txt.
  3. Download the following Bouncy Castle libraries:
  4. Place the downloaded libraries into ${JAVA_HOME}/jre/lib/ext directory.
  5. Update the java.security (i.e. found in ${JAVA_HOME}/jre/lib/security directory.) file to have the following as the priority:
    security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
    security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
    

    Adjust the other security.provider to start from 3 like the following:

    security.provider.3=sun.security.provider.Sun
    security.provider.4=sun.security.rsa.SunRsaSign
    security.provider.5=com.sun.net.ssl.internal.ssl.Provider
    security.provider.6=com.sun.crypto.provider.SunJCE
    security.provider.7=sun.security.jgss.SunProvider
    security.provider.8=com.sun.security.sasl.Provider
    security.provider.9=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    security.provider.10=sun.security.smartcardio.SunPCSC
    security.provider.11=sun.security.mscapi.SunMSCAPI
    
  6. Try the following Java code:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.ProtocolException;
    import java.net.URL;
    
    public class Main {
    
        public static void main(String[] args) {
            try {
                URL url = new URL("https://www.nist.gov/");
                System.out.println(url);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(true);
                System.out.println(connection.getResponseCode());
                StringBuilder response = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
                try {
                    String line = reader.readLine();
                    while (line != null) {
                        response.append(line);
                        line = reader.readLine();
                    }
                } finally {
                    reader.close();
                }
    
                System.out.println(response.toString());
            }
            catch(ProtocolException exception) {
                exception.printStackTrace();
            }
            catch(IOException exception) {
                exception.printStackTrace();
            }
        }
    }

    You should be able to access it without any SSL handshake error.

    Alternatively, you can opt to use the official JDK 6u121 via the Java SE 6 Advanced and Java SE 6 Support if you have availed of it.

Publishing to Maven Central with Gradle

Pre-requisites

  1. Create an account to sonatype.
  2. Request for a group id from sonatype by using Jira to create an issue.
  3. Generate PGP keys to be used for signing the binaries (e.g. jar file). For windows, you can follow the procedure here.
  4. Wait for the completion of the issue you've created from item 2.

Gradle Configuration

  1. Update your gradle.properties to include the following properties:
    nexusUsername=<SONATYPE_USERNAME>
    nexusPassword=<SONATYPE_PASSWORD>
    
    signing.keyId=<PGP_PUBLIC_KEY_ID>
    signing.password=<PGP_PASS_PHRASE>
    signing.secretKeyRingFile=<PGP_EXPORTED_PRIVATE_KEY>
    
  2. In your build.gradle file,  add the Gradle Sonatype Nexus Plugin like the following:
    plugins {
       id "java"
       id "com.bmuschko.nexus" version "2.3.1" // Gradle Sonatype Nexus Plugin
    }
  3. Add the following plugin configurations:
    modifyPom {
        project {
            name '<PROJECT_NAME>'
            description '<PROJECT_DESCRIPTION>'
            url '<PROJECT_WEBSITE>'
            inceptionYear '<PROJECT_INCEPTION_YEAR>'
    
            scm {
                url '<PROJECT_SCM_ADDRESS>'
                connection '<PROJECT_SCM_ADDRESS>'
                developerConnection '<PROJECT_SCM_ADDRESS>'
            }
    
            licenses {
                license {
                    name '<PROJECT_LICENSE_NAME>'
                    url '<PROJECT_LICENSE_ADDRESS>'
                    distribution 'repo'
                }
            }
    
            developers {
                developer {
                    id '<DEVELOPER_ID>'
                    name '<DEVELOPER_NAME>'
                    email '<DEVELOPER_EMAIL>'
                }
            }
        }
    }
    
    extraArchive {
        sources = true
        tests = true
        javadoc = true
    }
    
    nexus {
        sign = true
        repositoryUrl = '<SONATYPE_RELEASE_REPOSITORY>'
        snapshotRepositoryUrl = '<SONATYPE_SNAPSHOT_REPOSITORY>'
    }
  4. Add the Gradle Nexus Staging plugin like the following:
    plugins {
        id 'java'
        id "com.bmuschko.nexus" version "2.3.1" // Gradle Sonatype Nexux Plugin
        id "io.codearte.nexus-staging" version "0.21.1" // Gradle Nexus Staging Plugin
    }
  5. After adding the plugin save the build.gradle file.
  6. Get the staging profile ID by running the following command:
    gradlew getStagingProfile
  7. Add the following plugin configuration:
    nexusStaging {
        stagingProfileId = "<STAGING_PROFILE_ID>"
    }
  8. Save the build.gradle file again.

Uploading to Sonatype Repository

Run the following command:

gradlew publishToSonatype

Publishing to Maven Central

Run the following command:

gradlew closeAndReleaseSonatypeStagingRepository

Errors in Publishing

If there are any errors after running the preceding command

  1. Sign in to the following address using your sonatype credentials: https://oss.sonatype.org/
  2. Click the Staging Repositories menu and investigate the error from there.
  3. Once the errors were identified and corrected locally, upload it again to sonatype repository before publishing it again.

Do this error correction process until all the errors were corrected.

Successful Publishing Validation

After around 10 minutes, navigate to your registered group id from sonatype, starting from the following address:

https://repo.maven.apache.org/maven2/

After around 2 hours, your artifact id may be searchable in maven central from the following address:

https://search.maven.org/

 

Java Proxy Properties By Protocol

Common Protocols

Protocol proxyHost proxyPort nonProxyHosts proxyUser proxyPassword
http Y Y Y Y Y
https Y Y also use http.nonProxyHosts Y Y
ftp Y Y Y Y Y

For nonProxyHosts, a list of hosts that should be reached directly without the proxy. The list is separated by '|' (i.e. pipe symbol). The patterns may start or end with a '*' for wildcards.

If the protocol value is Y for a particular header, it means you can combine the protocol with the header (e.g. http is Y for proxyHost in the table, thus we can combine it as http.proxyHost) to form a single property.

SOCKS Protocol

Property Description
socksProxyHost The host of the SOCKS proxy server.
socksProxyPort The port (i.e. defaulting to 1080) where SOCKS proxy server is listening.
socksProxyVersion The version (i.e. defaulting to 5) of the SOCKS protocol supported by the server.
java.net.socks.username The username for authenticating to SOCKSv5 proxy server.
java.net.socks.password The password for authenticating to SOCKSv5 proxy server.

System Proxy

java.net.useSystemProxies set this property to true to use the system proxy.

Simple Example of Using Some of the Properties

java -Dhttp.proxyHost=localhost -Dhttp.proxyPort=808 ApplicationAccessingTheNet

Listing the Entries of a Java Keystore

Use the following command to list the entries of a Java keystore:

The keytool is normally found in $JAVA_HOME/jre/bin (i.e. the $JAVA_HOME variable is where you’ve installed JDK).

keytool -list -v -keystore <KEYSTORE_FILE> -storepass <KEYSTORE_PASSWORD>

Include the -a <ALIAS> parameter to just display a single certificate.

Token Description
KEYSTORE_FILE The target key store file (e.g. cacerts found in $JAVA_HOME/jre/lib/security)
KEYSTORE_PASSWORD The password for accessing the keystore (i.e. the default is changeit)

Importing a Certificate to Java Keystore

Use the following command in importing a certificate to Java keystore:

The keytool is normally found in $JAVA_HOME/jre/bin (i.e. the $JAVA_HOME variable is where you've installed JDK).

keytool -importcert -alias <ALIAS> -v -keystore <KEYSTORE_FILE> -file <INPUT_FILE> -storepass <KEYSTORE_PASSWORD>
Token Description
ALIAS Alias name of the entry to process
KEYSTORE_FILE The target key store file (e.g. cacerts found in $JAVA_HOME/jre/lib/security)
INPUT_FILE Input file name (i.e. certificate file like cer, crt or pem)
KEYSTORE_PASSWORD The password for accessing the keystore (i.e. the default is changeit)

 

Basic log4j.properties for console and file output

# Root logger option
log4j.rootLogger=INFO, file, stdout

# Console output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%m%n

# File output
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%t - %m%n

Install Jabba in Powershell behind proxy

Jabba is a java version manager (see https://github.com/shyiko/jabbathat simplifies the installation and switching of/to different JDK.

If your powershell is behind the firewall follow the procedure here.

Install Jabba using the following cmdlet:

Note: If you encountered something like jabba.ps1 cannot be loaded because running scripts is disabled on this system. For
more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170 see running unsigned script.

Invoke-Expression (
        wget https://github.com/shyiko/jabba/raw/master/install.ps1 -UseBasicParsing
    ).Content

Calling Web Service without Generating Stubs (JAX-WS API)

Introduction

Normally calling a SOAP WebAPI requires the developer to access WSDL then based on it generates the stubs linked to a particular server. After generating it, we need to compile those to make them ready to be used. The problem with that one is. Do we use the same server for development, testing and production? If yes, we need to regenerate the stubs for testing and if we are satisfied with the testing. We need to regenerate the stubs for production. Wait? The one tested is not really the one going to production. The simplest way to do is not to generate the stubs but understand how the soap message was structured. If we know the structure of the SOAP message (i.e. SOAP UI can be used here), then we can create it by hand. The following is the sample of assembling a SOAP message for invoking the evaluate method from the StudioService endpoint of PolicyCenter 7 (i.e. One of the Centers of Guidewire) using Java.

Code 1. Using JAXWS API with Java

import java.util.Iterator;

public class GWStudioService {

    public static void main(String[] args) throws SOAPException, IOException {
        String endpointUrl = "http://localhost:8180/pc/ws/gw/internal/webservice/studio/StudioService";
        String targetNamespace = "http://guidewire.com/pl/ws/gw/internal/webservice/studio/StudioService";

        QName serviceName = new QName(targetNamespace,"evaluateGosu");
        QName portName = new QName(targetNamespace,"StudioServiceSoap12Port");

        /** Create a service and add at least one port to it. **/
        Service service = Service.create(serviceName);
        service.addPort(portName, SOAPBinding.SOAP12HTTP_BINDING, endpointUrl);

        /** Create a Dispatch instance from a service.**/
        Dispatch dispatch = service.createDispatch(portName,
                SOAPMessage.class, Service.Mode.MESSAGE);

        /** Create SOAPMessage request. **/
        // compose a request message
        MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

        // Create a message.  This example works with the SOAPPART.
        SOAPMessage request = mf.createMessage();
        SOAPPart part = request.getSOAPPart();

        // Obtain the SOAPEnvelope and header and body elements.
        SOAPEnvelope env = part.getEnvelope();
        SOAPHeader header = env.getHeader();
        SOAPBody body = env.getBody();

        String authNS = "http://guidewire.com/ws/soapheaders";

        SOAPElement auth = header.addChildElement("authentication", "auth", authNS);
        SOAPElement username = auth.addChildElement("username", "auth");
        username.addTextNode("su");
        SOAPElement password = auth.addChildElement("password", "auth");
        password.addTextNode("gw");

        // Construct the message payload.
        SOAPElement operation = body.addChildElement("evaluateGosu", "stud",
                targetNamespace);
        SOAPElement value = operation.addChildElement("code", "stud");
        value.addTextNode("7072696e74282248656c6c6f20776f726c642229");
        request.saveChanges();

        System.out.println("Request\n");
        request.writeTo(System.out);

        SOAPMessage response = dispatch.invoke(request);

        System.out.println("\n\nResponse\n");
        response.writeTo(System.out);

        SOAPPart inSOAPPart = response.getSOAPPart();
        SOAPEnvelope inEnv = inSOAPPart.getEnvelope();
        SOAPBody inBody =  inEnv.getBody();

        Iterator inGosuResp = inBody.getChildElements(new QName(targetNamespace, "evaluateGosuResponse"));
        Iterator inReturn = inGosuResp.next().getChildElements(new QName(targetNamespace, "return"));
        Iterator inEntries= inReturn.next().getChildElements(new QName(targetNamespace, "Entry"));

        while (inEntries.hasNext()) {
            SOAPElement inEntry = inEntries.next();

            System.out.println(">");
            System.out.println(inEntry.getElementName().getLocalName());
            System.out.println(inEntry.getTextContent());
        }
    }
}

Output 1: Sample output of running code 1

<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Header/><soap12:Body><evaluateGosuResponse xmlns="http://guidewire.com/pl/ws/gw/internal/webservice/studio/StudioService">

<return>

<Entry>48656C6C6F20776F726C640D0A</Entry>

<Entry/>

</return>

</evaluateGosuResponse></soap12:Body></soap12:Envelope>

To understand the output of the entry we can use the following online Hex to String converter.

https://codebeautify.org/hex-string-converter

Reference:

https://axis.apache.org/axis2/java/core/docs/jaxws-guide.html#DispatchClient

« Older posts Newer posts »