Translate

Saturday, August 29, 2015

Java - Authenicate against Active Directory

It turns out it's very easy using JNDI to authenticate someone against Active Directory.

/**
 * Authenticate against AD
 * @param username The user name
 * @param password The password
 * @return True if authenticate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean authenicate(String username, String password){
 boolean bRes = true;
 ResourceBundle rsBun = ResourceBundle.getBundle("LDAP_Res");
 Hashtable env = new Hashtable();
 env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
 //Use the secure connection
 env.put(Context.PROVIDER_URL, rsBun.getString("urls"));
 //Add the domain name if the user name does not contain it
 if (username.indexOf(rsBun.getString("domain")) == -1){
  username = rsBun.getString("domain") + "\\" + username;
 }
 env.put(Context.SECURITY_PRINCIPAL, username); 
 env.put(Context.SECURITY_CREDENTIALS, password); 
 try {
  LdapContext ctx = new InitialLdapContext(env,null);
  ctx.close();
 } catch (NamingException e) {
  bRes = false;
 } 
 return bRes;
}

Saturday, August 15, 2015

Java - Using web socket for push notifications

I was working on a small web application that had a long running server process and I thought it would be good to send a progress notification back to the user. The client is identified on the server by their session.

The controller:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;


@ServerEndpoint(value = "/mainwebsock", 
        configurator = GetHttpSessionConfigurator.class)
public class MainControllerWebSocket {
 private static Map mSessions = new HashMap();
 
 @OnMessage
 public void onMessage(String message, Session session) throws IOException,
   InterruptedException {
  System.out.println("User input: " + message);
  session.getBasicRemote().sendText("Hello world Mr. " + message);
  // Sending message to client each 1 second
  for (int i = 0; i <= 6; i++) {
   session.getBasicRemote().sendText(i + " Message from server");
   Thread.sleep(1000);

  }
 }
 
 public static void sendMessage(String message, String strSessionID){
  try {
   @SuppressWarnings("resource")
   Session mySes = mSessions.get(strSessionID);
   if (mySes != null && mySes.isOpen()) mySes.getBasicRemote().sendText(message);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

    @OnOpen
    public void open(Session session, EndpointConfig config) {
     HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        mSessions.put(httpSession.getId(), session);
        System.out.println("Client connected on session: " + httpSession.getId());
    }

 @SuppressWarnings("rawtypes")
 @OnClose
 public void onClose(Session session) {
  for (Iterator iter = mSessions.entrySet().iterator(); iter.hasNext();) {
     @SuppressWarnings("unchecked")
   Map.Entry  e = (Entry) iter.next();
     if (e.getValue().getId() == session.getId() ) {
      iter.remove();
     }}
  System.out.println("Connection closed");
 }
}


The session configurator:

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator
{
    @Override
    public void modifyHandshake(ServerEndpointConfig config, 
                                HandshakeRequest request, 
                                HandshakeResponse response)
    {
        HttpSession httpSession = (HttpSession)request.getHttpSession();
        config.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
}

The JavaScript:

var webSocket = null;

function connect() {
 var wsURI = 'ws://' + window.location.host + '/INagresso/mainwebsock';
 console.log("Connecting");
 webSocket = new WebSocket(wsURI);
 
 webSocket.onerror = function(event) {
  displayMessage(event.data);
 };
 
 webSocket.onopen = function(event) {
  displayMessage("Connection open.");
 };
 
 webSocket.onmessage = function(event) {
  displayMessage(event.data);
 };
 
}


function displayMessage(data) {
document.getElementById('main_content').innerHTML += '
' + data; } function disconnect() { if (webSocket !== null) { webSocket.close(); webSocket = null; } displayMessage("WebSocket closed."); } //Button click handler function createADAcccount(){ if (webSocket == null) {connect();} $('div#main_content').empty(); $('li#value_input').html('<h1>Create AD Accounts</h1>'); $("div#main_content").load('${pageContext.request.contextPath}/testCreateAccountsAD'); }

In any server process when we want to send a message to the web client we call:

//strMessage is the message we want to send 
//and mySession.getId() is the HttpSession Id
MainControllerWebSocket.sendMessage(strMessage, mySession.getId());
Git Project

SharePoint 2013 - Start or Stop Search

Starting search using the Services Control Manager in Windows will cause problems with your SharePoint Server. The search service should be started or stopped using SharePoint Central Administration or Power Shell. When I used the Services Control Manager to start the Search Host Controller Service I would get the following error:

The Execute method of job definition Microsoft.Office.Server.Search.Administration.CustomDictionaryDeploymentJobDefinition (ID 1371766a-f3a1-4d40-a1d9-7464c0b2b2cb)
threw an exception. More information is included below.
and this in the SharePoint Log:

TCP error code 10061: No connection could be made because the target machine actively refused it 10.10.40.160:808
After this error the search service would be stopped by SharePoint and show as disabled in the Services Control Manager in Windows.

Thursday, August 13, 2015

SharePoint 2013 - Search Crawl Index Reset Error

I was working on the getting search set up and the crawl was not working. Doing a "Index Rest" would eventually time out and when I looked at the error using the ULS Viewer I found "Application error when access /_admin/search/searchreset.aspx, Error=No connection could be made because the target machine actively refused it." In my case the problems were caused by the "SharePoint Search Host Controller" service being disabled.

Tuesday, August 11, 2015

SharePoint 2013 Site Settings URL

Working on migrating our SharePoint from 2010 to 2013. I did the upgrade of the content database but then I couldn't get to the site settings because of a file not found exception. What I found I could do is go directly to the settings URL "http://xxx/_layouts/15/settings.aspx". Once there I went to "Master page" under "Look and Feel" changed the Site Master Page and System Master Page to one of the standard pages.