{{error}}
{{(quickSearchResults.length>10)?'10+':(quickSearchResults.length)}} {{(quickSearchResults.length==1)?'result':'results'}}
{{result.title}} {{result.timeStamp | mysql2ymd }}
I am sorry, no such article was written yet.
2017-08-03
Sample code that prompts when new server certificates found, and if confirmed, they are saved on disk for further usage.
1 files attached: SSLTest.java
SSLTest.java
package main;

import sun.misc.BASE64Encoder;
import sun.misc.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.callback.ConfirmationCallback;
import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.stream.Stream;

public class SSLTest{
    interface FlexSupplier<T>{
        T get() throws Throwable;
    }

    private static <T> T Try(FlexSupplier<T> function){
        try{
            return function.get();
        }catch(Throwable throwable){
            throw new RuntimeException(throwable);
        }
    }

    private static X509Certificate[] getSavedCertificates(){
        CertificateFactory x509=Try(()->CertificateFactory.getInstance("X.509"));
        return Stream.of(new File("c:\\workingFolder").listFiles())
                       .filter(it->it.getName().endsWith(".cer"))
                       .map(it->Try(()->new FileInputStream(it)))
                       .map(file->Try(()->x509.generateCertificate(file)))
                       .toArray(X509Certificate[]::new);
    }

    private static void saveCertificate(X509Certificate certificate){
        Try(()->Files.write(new File("c:\\workingFolder\\"+certificate.getSerialNumber()+".cer").toPath(),certificate.getEncoded()));
    }

    private static boolean matches(X509Certificate savedCertificate,X509Certificate newCertificate){
        if(savedCertificate.getSerialNumber().equals(newCertificate.getSerialNumber()))
            return true;
        try{
            newCertificate.verify(savedCertificate.getPublicKey());
            return true;
        }catch(Throwable t){
            return false;
        }
    }

    private static void validateCertificate(X509Certificate it){
        System.out.println("Checking certificate: "+it.getSubjectDN());
        for(X509Certificate saved : getSavedCertificates())
            if(matches(saved,it)){
                System.out.println("Matched by: "+saved.getSubjectDN()+" by "+saved.getIssuerDN());
                return;
            }
        System.out.println("Not matched!!!");
        if(promptFor(it))
            saveCertificate(it);
        else throw new RuntimeException("Certificate rejected");
    }

    private static boolean promptFor(Certificate it){
        X509Certificate x=(X509Certificate)it;
        String message=x.getNotBefore()+"-"+x.getNotAfter()+"\r\n";
        message+=x.getIssuerDN()+" by "+x.getIssuerX500Principal()+"\r\n";
        message+=x.getSerialNumber()+"\r\n";
        message+=new BASE64Encoder().encode(x.getSignature());
        return JOptionPane.showConfirmDialog(null,message)==ConfirmationCallback.YES;
    }

    public static void main(String[] args) throws IOException{
        trustSavedCertificates();
        URL url;
        url=new URL("https://host/domain");
        HttpsURLConnection con=(HttpsURLConnection)url.openConnection();
        System.out.println(new String(IOUtils.readFully(con.getInputStream(),-1,true)));
    }


    public static void trustSavedCertificates(){
        TrustManager[] trustAllCerts=new TrustManager[]{
                new X509TrustManager(){
                    public X509Certificate[] getAcceptedIssuers(){
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs,String authType){
                    }

                    public void checkServerTrusted(X509Certificate[] certs,String authType){
                        for(X509Certificate cert : certs)
                            validateCertificate(cert);
                    }
                }
        };
        try{
            SSLContext sslContext=SSLContext.getInstance("SSL");
            sslContext.init(null,trustAllCerts,new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}
How to retrieve server certificates, save them, and use their public keys to validate new connections
How to retrieve server certificates, save them, and use their public keys to validate new connections
3 files attached: SSLTest.java findCertificates.java validateUsingCertificates.java
SSLTest.java findCertificates.java
URL url = new URL("https://server/");
List<String> certificateStrings = getAllCertificateStrings(url);
// save the relevant certificates on your disk
validateUsingCertificates.java
URL url = new URL("https://server/");
List<String> certificateStrings = getAllCertificateStrings(url);// or load them from disk
List<PublicKey> publicKeys = certificateStrings.stream().map(it -> Try(() -> base64certificate2publicKey(it))).collect(Collectors.toList());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setHostnameVerifier(verifier(publicKeys));
System.out.println(new String(IOUtils.readFully(con.getInputStream(), -1, true)));
Basic NTLM for HTTP server-side without third message validation on issuing server
1 files attached: NTLM.java
NTLM.java
package dms.net.http;

import java.io.IOException;
import java.util.Random;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class NTLM {
	private static final NTLM NTLM_0 = new NTLM(0, new byte[0]);
	private byte[] data;
	public final int version;
	public final String challenge;
	public String domain;
	public String workstation;
	public String userName;
	public String host="";
	public String ip="";

	public static NTLM getNTLM(String auth) {
		byte[] data;
		NTLM result = NTLM_0;
		if (auth == null)
			return result;
		try {
			data = new BASE64Decoder().decodeBuffer(auth.substring(5));
		} catch (IOException e) {
			return result;
		}
		int version = data[8] + data[9] * 256;
		if (version == 0)
			return result;
		return new NTLM(version, data);
	}

	private NTLM(int version, byte[] data$) {
		this.version = version;
		this.data = data$;
		if (this.version == 0) {
			challenge = "NTLM";
		} else if (this.version == 1) {
			challenge = "NTLM "
					+ new BASE64Encoder().encodeBuffer(
							new byte[] { 'N', 'T', 'L', 'M', 'S', 'S', 'P', 0,
									2, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 1,
									(byte) 0x82, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8,
									0, 0, 0, (byte) new Random().nextInt(100), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
									0, 0, 'N', 'T', 'N', 'E', 'T' }).trim();
			readInt(8);
			if (!readAsciiString(0, 8).equals("NTLMSSP\0"))
				return;
			if (readInt(8) != 1)
				return;
			readInt(12);
			this.domain = readSecurityBuffer(16);
			this.workstation = readSecurityBuffer(24);
		} else if (this.version == 3) {
			challenge = null;
			readInt(8);
			if (!readAsciiString(0, 8).equals("NTLMSSP\0"))
				return;
			if (readInt(8) != 3)
				return;
			this.domain = readSecurityBuffer(28);
			this.workstation = readSecurityBuffer(44);
			this.userName = readSecurityBuffer(36);
		} else {
			challenge = null;
		}
	}

	private String readAsciiString(int pos, int len) {
		char[] result = new char[len];
		for (int i = 0; i < len; i++)
			result[i] = (char) this.data[pos + i];
		return new String(result);
	}

	private int readInt(int pos) {
		int result = 0;
		for (int i = 0; i < 4; i++)
			result = this.data[pos++] << 24 | (0x00ffffff & (result >> 8));
		return result;
	}

	private short readShort(int pos) {
		short result = 0;
		for (int i = 0; i < 2; i++)
			result = (short) (this.data[pos++] << 8 | (result >> 8));
		return result;
	}

	private String readSecurityBuffer(int pos) {
		String result = "";
		int length = readShort(pos);
		readShort(pos + 2);
		int offset = readInt(pos + 4);
		try {
			String temp = readAsciiString(offset, length);
			for (int i = 0; i < temp.length(); i++)
				if (temp.charAt(i) != 0)
					result += temp.charAt(i);
		} catch (ArrayIndexOutOfBoundsException e) {
			throw e;
		}
		return result;
	}
}
Easy wrapper for querying the LDAP from Java
Easy wrapper for querying the LDAP from Java using only JDK.
2 files attached: LdapConnector.java SampleUsage.groovy
LdapConnector.java SampleUsage.groovy
@Memoized
List<Map<String, List<?>>> getAllLdapUserGroups() { connector["(&(cn=GROUP_*)(objectclass=groupOfUniqueNames))"] }

 public LdapRecord getAt(User user) {
        List<LdapRecord> result = connector['uid=' + user.uid];
        if (result.size() == 0) return null;
        if (result.size() == 1) return result.first()
        throw new IllegalArgumentException("Too many results found for $user")
    }

 public static void main(String[] args) {
        println ApiTest.$$.ldap.allUserGroups
}
Scriptless Angular toggle snippet
Not really scriptless - Angular runs the script.
No need to define variable in scope.
1 files attached: angularScriptlessToggle.html
angularScriptlessToggle.html
<table class='table table-bordered table-hover table-condensed table-compressed table-striped' style='width:auto; float:right'>
				<caption ng-click='toggleSummaryTable = !toggleSummaryTable'>Summary aggregate</caption>
				<thead ng-show='toggleSummaryTable'>
					<tr>
						<th ng-repeat='header in logData.summary.headers'>{{header}}</th>
					</tr>
				</thead>
				<tbody ng-show='toggleSummaryTable'>
					<tr ng-repeat='record in logData.summary.data'>
						<td ng-repeat='header in logData.summary.headers'>{{record[header]}}</td>
					</tr>
				</tbody>
			</table>
regular expression custom jQuery selector
1 files attached: jQuery.matches.js
jQuery.matches.js
var REGEXP_CACHE = {};

jQuery.expr[":"].matches = function (obj, index, meta, stack) {
    var expression = meta[3];
    var regexp = REGEXP_CACHE[expression] = REGEXP_CACHE[expression] || new RegExp("^" + expression + "$", "gim");
    var jElem = jQuery(obj);
    return (regexp.test((String(jElem.text())).trim()))
        || (regexp.test((String(jElem.val())).trim()))
        || (regexp.test((String(jElem.attr("placeholder"))).trim()))
};
sQuery - DOM proximity relevance
sQuery - easier way to identify HTML objects by jQuery CSS selectors. Identification based on DOM proximity relevance.
1 files attached: sQuery.js
sQuery.js
building an animation in R based on images from a folder
1 files attached: animationDraft.r
animationDraft.r
captures="\\\\raspberrypi\\hdd500gb\\surveillance\\captures"
cameras <- c('Poarta','Curte')
for(camera in cameras){
  #print(camera)
  #print(list.files())
  cameraFolder<-paste(captures,camera,sep="\\")
  print(cameraFolder)
  cameraDays <- list.files(cameraFolder)
  print(cameraDays)
  for(cameraDay in cameraDays){
    cameraImages<-list.files(paste(captures,camera,cameraDay,sep="\\"))
    print(length(cameraImages))
    firstHourImages<-(cameraImages[Vectorize(function(x){substr(x,8,11)<"0030"})(cameraImages)])
    firstHourImages<-rapply(list(firstHourImages),function(x){magick::image_read(paste(captures,camera,cameraDay,x,sep="\\"))})
    animation<-magick::image_animate(magick::image_join(firstHourImages))
    magick::image_write(animation,paste("c:\\users\\dragosmateis\\desktop\\ccc",camera,cameraDay,sep="_"),format = )
    #print(firstHourImages)
  }
}
2017-02-21
How to hide Spock stack traces when running tests written in Groovy.
2 files attached: IgnoreStackraceElements.groovy MyException.java
IgnoreStackraceElements.groovy
static {
        StackTraceUtils.addClassTest({ String className ->
            if (className.startsWith("org.spockframework.")) return false;
            return null;
        });
    }
MyException.java
import org.codehaus.groovy.runtime.StackTraceUtils;
public class MyException extends RuntimeException {
    public MyException(String message, Object... suppressed) {
        super(message);
        for (Object t : suppressed)
            if (t instanceof Throwable) this.addSuppressed(StackTraceUtils.deepSanitize((Throwable) t));
        StackTraceUtils.deepSanitize(this);
    }
}
Scala JSON Comparator
4 files attached: JsonComparator.scala left.json right.json output.txt
JsonComparator.scala
import scala.io.Source
import scala.util.parsing.json._

object JsonComparator {
  def compare(left: Any, right: Any, path: java.lang.String = ""): List[String] = (left, right) match {
    case (l: Number, r: Number) => if (l == r) Nil else s"$path: $l != $r" :: Nil
    case (l: String, r: String) => if (l == r) Nil else s"$path: $l != $r" :: Nil
    case (l: Set[_], r: Set[_]) => if (l == r) Nil else s"$path: $l != $r" :: Nil
    case (l: List[_], r: List[_]) =>
      if (l == r) Nil
      else if (l.length != r.length) s"$path.length: ${l.length} vs. ${r.length}" :: Nil
      else l.indices.toList.filter(it => l(it) != r(it)).flatMap(it => compare(l(it), r(it), s"$path[$it]"))
    case (l: Map[String, _], r: Map[String, _]) =>
      if (l == r) Nil
      else if (l.size != r.size) s"$path.count: ${l.size} != ${r.size}" :: Nil
      else if (l.keySet != r.keySet) s"$path.keys: ${l.keySet} != ${r.keySet}" :: Nil
      else l.keySet.toList.filter(it => l(it) != r(it)).flatMap(it => compare(l(it), r(it), s"$path/$it"))
    case _ =>
      s"$path: $left[${if (left == null) left else left.getClass}] vs. $right[${if (right == null) right else right.getClass}]" :: Nil
  }

  def main(args: Array[java.lang.String]): Unit = {
    val left = JSON.parseFull(Source.fromResource("left.json").mkString)
    val right = JSON.parseFull(Source.fromResource("right.json").mkString)
    compare(left.get, right.get).foreach(println)
    compare(left.get, left.get).foreach(println)
  }
}
left.json
{"node1": [1, 2, ["q","w"], "e"], "node2": {"node3": "value4","null": null}, "node3": 3, "node4": 4, "node5": 5.5}
right.json
{"node1": [1, "3", ["q", "w", 0], "e"], "node2": {"node3": "value4", "null": "null"}, "node3": "3", "node4": 4, "node5": 5.6}
output.txt
/node1[1]: 2.0[class java.lang.Double] vs. 3[class java.lang.String]
/node1[2].length: 2 vs. 3
/node3: 3.0[class java.lang.Double] vs. 3[class java.lang.String]
/node2/null: null[null] vs. null[class java.lang.String]
/node5: 5.5 != 5.6