Translate

Tuesday, May 29, 2012

Internews - Learn to Communicate with Crisis-Affected Communities

A new, free online learning course, Communication is Aid, aims to raise awareness and build basic skills for communicating effectively with crisis-affected communities, before and after an emergency breaks.

Read the rest of the story here.

Wednesday, May 23, 2012

Internews - Armenian Media Pioneer Hopes to Engage the Public through Citizen Reporting Gaming Platform

In October 2010, Armenian schoolchildren documented numerous cases of physical abuse at the hands of teachers using the cameras on their mobile phones. However, as Armenian journalist Seda Muradyan noted in her 2011 Knight Fellowship presentation at Stanford University, few people saw the videos until six months or even a year after they were shot, when they were uploaded online and swiftly went viral.

Read the rest of the story here.

Monday, May 21, 2012

Java - Calculate Date Frequency

I needed to calculate the biweekly, monthly, or quarterly date frequency and create a list of dates. It's easy using Joda Time.


Here is my Java class. Just pass the start date and end date to the method.

package org.inewsnet.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.joda.time.LocalDate;
import org.joda.time.Period;

/**
 * Methods to calculate biweekly, monthly, and quarterly date  frequencies
 * @author Richard Golebiowski
 *
 */
public class DateTimeService {
    /**
     * Calculates the dates for the Biweekly frequency
     * @param dtStart  the tart date
     * @param dtEnd    the end date
     * @return         a list of dates
     */
    public List<Date> getBiwekly(Date dtStart, Date dtEnd){
        List <Date> lstDate = new ArrayList<Date>();
        LocalDate start = new LocalDate(dtStart);
        LocalDate end = new LocalDate(dtEnd);
        Period period = Period.weeks(2);
        Period current = Period.ZERO;
        while (true) {
            LocalDate candidate = start.plus(current);
            if (candidate.isEqual(end) || candidate.isAfter(end)) {
                lstDate.add(dtEnd); 
                return lstDate;
            }
            else {
                lstDate.add(candidate.toDate());      
            }
            current = current.plus(period);
        }
    }
    
    /**
     * Calculates the dates for the Monthly frequency
     * @param dtStart  the tart date
     * @param dtEnd    the end date
     * @return         a list of dates
     */
    public List<Date> getMonthly(Date dtStart, Date dtEnd){
        List <Date> lstDate = new ArrayList<Date>();
        LocalDate start = new LocalDate(dtStart);
        LocalDate end = new LocalDate(dtEnd);
        Period period = Period.months(1);
        Period current = Period.ZERO;
        while (true) {
            LocalDate candidate = start.plus(current);
            if (candidate.isEqual(end) || candidate.isAfter(end)) {
                lstDate.add(dtEnd); 
                return lstDate;
            }
            else {
                lstDate.add(candidate.toDate());                
            }
            current = current.plus(period);
        }
    }

    /**
     * Calculates the dates for the Quarterly frequency
     * @param dtStart  the tart date
     * @param dtEnd    the end date
     * @return         a list of dates
     */
    public List<Date> getQuarterly(Date dtStart, Date dtEnd){
        List <Date> lstDate = new ArrayList<Date>();
        LocalDate start = new LocalDate(dtStart);
        LocalDate end = new LocalDate(dtEnd);
        Period period = Period.weeks(13);
        Period current = Period.ZERO;
        while (true) {
            LocalDate candidate = start.plus(current);
            if (candidate.isEqual(end) || candidate.isAfter(end)) {
                lstDate.add(dtEnd); 
                return lstDate;
            }
            else {
                lstDate.add(candidate.toDate());                
            }
            current = current.plus(period);
        }
    }
     
}

Friday, May 18, 2012

Internews - New Report: Closing the Loop — Responding to Information Needs in Haiti

Information matters, especially for individuals affected by severe crises like the 2010 earthquake in Haiti. But critically, new research shows that listening to audiences may be just as important.

Read the rest of the story here.

JQuery Offset Error

I was working on a drop-down menu that was fixed at the top of the page. It worked in Firefox, but not IE or Chrome. By using the developer tools in Chrome I discovered that there was an error on getting the offset position. The error message was "Cannot read property 'tagName' of null" and was being caused by the jQuery dimensions plugin. This plugin was used by the previous menu and wasn't needed any more so I removed it and the drop-down menus worked!

Friday, May 11, 2012

Using SQL to make a SharePoint Contact List

I needed to make a list of contact information for all of our offices using the contact information in Active Directory. All of the "regular" solutions were not applicable because the offices were contained in the same Organizational Unit as some other contacts, requiring the offices be filtered out from the other contacts. The solution was to use the SQL server that is used to host the databases for the SharePoint site to query AD and return the filtered list.

The first step is to create the SQL Linked server. I used SQL Management Studio to do this. Under "Server Objects, right click on "Linked Servers" and the click "New Linked Server".

Here are the settings you need to make. The "Data Source" is the name of your AD server.

On the "Security" page, enter the security settings:


Create the view:

CREATE VIEW [dbo].[vwWxyzOffices]
AS
SELECT sn[Country], homephone[Business Phone], l[City], streetAddress[Street Address], postalCode[Postal Code],
mail[Email], facsimileTelephoneNumber[Fax], mobile[Mobile Phone], info[Notes], wWWHomePage[Website]
FROM OPENQUERY(ADSI,
'SELECT givenName, sn, homephone, l, streetAddress, postalCode, facsimileTelephoneNumber,
mail, mobile, info, wWWHomePage
FROM ''LDAP://OU=Contacts,DC=Wxyz,DC=local''
WHERE objectClass = ''contact''  and givenName = ''Wxyz''')
GO

Finally, add the view into SharePoint as an external data source and use it in your SharePoint list!

Sunday, May 6, 2012

Tables Not Rendering Correctly in IE9

In the application that I'm working on I discovered that large tables were not rendering correctly in Internet Explorer 9. The same pages displayed correctly in IE8, Firefox, and Google Chrome. My first thought was that there was a problem in my page layout that only affected IE9. I looked over the HTML but couldn't find anything wrong. What I did notice was a large amount of white space. I wondered if that could cause the problem so I added the following to the top of the JSP page to strip out the extra white space.

<%@ page trimDirectiveWhitespaces="true" %>

Problem solved!

Wednesday, May 2, 2012

JNDI - Read Active Directory User Information

Today I needed to read in some user information from Active Directory so that I could create entries for each user and the uers group meberships in a SQL table.

Here is the code I used for testing:

package org.inewsnet.ldap;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LdapJndi{
    @SuppressWarnings("rawtypes")
    Hashtable env;
    DirContext ctx;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public boolean  connect(){
        boolean bRes = true;
        ResourceBundle rsBun = ResourceBundle.getBundle("LDAP");
        env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://" + rsBun.getString("server") + ":" + 
           rsBun.getString("port") + rsBun.getString("root"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple"); 
        env.put(Context.SECURITY_PRINCIPAL, "cn=" + rsBun.getString("principal")); 
        env.put(Context.SECURITY_CREDENTIALS, rsBun.getString("credentials")); 
        try {
            ctx = new InitialDirContext(env);
        } catch (NamingException e) {
            e.printStackTrace();
            bRes = false;
        }
        return bRes;
    }

    public static String getCN(String cnName) {
        if (cnName != null && cnName.toUpperCase().startsWith("CN=")) {
            cnName = cnName.substring(3);
        }
        int position = cnName.indexOf(',');
        if (position == -1) {
            return cnName;
        } else {
            return cnName.substring(0, position);
        }
    }

    public static String getUserName(String upn) {
        int position = upn.indexOf('@');
        return upn.substring(0, position);
    }

    @SuppressWarnings("rawtypes")
    public boolean testNetworkRead() {
        boolean bRes = false;
        String firstName;
        String lastName;
        String userName;
        ResourceBundle rsBun = ResourceBundle.getBundle("LDAP");
        String bsaeOU = "ou=" + rsBun.getString("baseOU");
        SearchControls sc = new SearchControls();
        String[] attributeFilter = {"memberOf", "userPrincipalName", "sn", "givenName",  "cn", "mail" };
        sc.setReturningAttributes(attributeFilter);
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String filter = "(&(sn=*)(l=*))";

        try {
            NamingEnumeration results = ctx.search(bsaeOU, filter, sc);
            Integer iCx = 0;
            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                Attributes attrs = sr.getAttributes();
                iCx = iCx + 1;
                System.out.print(iCx + ")");
                Attribute attr = attrs.get("sn");
                lastName = attr.get().toString();
                System.out.print("ln= " + lastName);
                attr = attrs.get("givenName");
                if (attr != null) {
                    firstName = attr.get().toString();
                    System.out.print(" fn= " + firstName);
                }
                System.out.print("-");
                Attribute aupn = attrs.get("userPrincipalName");    
                userName = getUserName(aupn.get().toString());
                Attribute mattr = attrs.get("memberOf");
                System.out.println(" un= " + userName + ": ");        
                if(mattr != null) {
                    //loop through the memberof attribute to get each group
                    for ( Enumeration e1 = mattr.getAll() ; e1.hasMoreElements() ; ) {
                        System.out.println(getCN(e1.nextElement().toString()));
                    }
                }
            }//end while
            bRes = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }            
        return bRes;
    }
}

All you need to do is provide your own connection settings in the connect method. I'm getting mine from a properties file.

This is my test method calling the methods in the class above:

public String testLdapNetworkRead() throws Exception {
    LdapJndi myCon = new LdapJndi();
    try {
        if(myCon.connect()) myCon.testNetworkRead();
    } catch (Exception e) {
        this.errorMsg = e.getMessage();
        return ERROR;
    }
    successMsg = "Test Connect OK";
    return SUCCESS;
}