Pages

30 July, 2013

A Java proxy for MS SQL Server Reporting Services:

A Java Web application often uses a SQL Server database. SQL Server now comes bundled with a reporting tool, Reporting Services. RS has generated a lot of attention among developers since it first came on the market about a year ago. It is a full-featured reporting tool that includes a WYSIWYG report editor with scripting/programming capabilities, a delivery engine, and a powerful Web services interface. Using RS makes sense—not only from a cost perspective, but also because of the reduced development and deployment complexities compared with using a third-party vendor. This article explores such an integration scenario.

 For detailed explanation and  step by step understanding purpose please go through the below URL.  

http://www.javaworld.com/javaworld/jw-01-2005/jw-0110-sqlrs.html

 Sample Code :

1. First Create a servlet name as GetReportItem..

package com.shekarsana;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.ReportAuthenticator;

public class GetReportItem extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private final static boolean DEBUG = true;
    private final static String REPORT_SERVER_URL = "http://servername/ReportServer";
     private final static int BUFFER_SIZE = 2048;

    public void init(ServletConfig config) throws ServletException
    {
    super.init(config);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    try
    {
              String queryString = request.getQueryString();

        if (queryString.indexOf("cookie=") == -1)
        {
            System.out.println("\nGetReportItem - ERROR: No cookie parameter provided. Aborting.");
        return;
        }

        String cookie = queryString.substring(queryString.indexOf("cookie"), queryString.indexOf("&") + 1);

        queryString = queryString.replaceAll(cookie, "");
        cookie = cookie.substring(cookie.indexOf("=") + 1, cookie.length() - 1);

        String urlString = REPORT_SERVER_URL + "?" + queryString;

        if (DEBUG)
        {
        System.out.println("\nGetReportItem - Cookie: " + cookie);
        System.out.println("GetReportItem - Query String: " + queryString);
        System.out.println("GetReportItem - Send to URL: " + urlString);
        }

        if (queryString == null)
        {
                ServletOutputStream responseErrorStream = response.getOutputStream();
        responseErrorStream.println("GetReportItem - ERROR: No parameters have been provided.");
        responseErrorStream.close();
        return;
        }
        URL url = new URL(urlString);
        HttpURLConnection repCon = (HttpURLConnection) url.openConnection();
        Authenticator.setDefault(new ReportAuthenticator());
        repCon.setRequestMethod("GET");
        repCon.setRequestProperty("User-Agent", "Mozilla/5.0");
        repCon.setRequestProperty("Cookie", cookie);
        repCon.setUseCaches(false);
        repCon.setFollowRedirects(false);

        // Pipe Report Server's Output to the client using buffered streams.
        response.setContentType(repCon.getContentType());
        response.setHeader("Content-disposition", repCon.getHeaderField("Content-disposition"));
        InputStream repInStream = repCon.getInputStream();
        ServletOutputStream clientOutStream = response.getOutputStream();

        BufferedInputStream bis = new BufferedInputStream(repInStream);
        BufferedOutputStream bos = new BufferedOutputStream(clientOutStream);

        byte[] buff = new byte[BUFFER_SIZE];
        int bytesRead;

        while (-1 != (bytesRead = bis.read(buff, 0, BUFFER_SIZE)))
        {
        bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
        repInStream.close();
        clientOutStream.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    }

}

Step2 :


2.  Create a servlet name as ReportRequest.

package com.shekarsana;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import util.ReportAuthenticator;
import util.GetAvailableParameters;

public class ReportRequest extends HttpServlet
{
    private final static boolean DEBUG = true;
    private final static String REPORT_SERVER_URL = "http://ServerName/ReportServer";
    private final static String REPORT_PATH = "%2fMYReports%2f";
    private final static String REPORT_ITEM_SERVLET_URL = "http://localhost:8080/SANA/GetReportItem"
    private final static int BUFFER_SIZE = 2048;

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            if(DEBUG)
            {
                System.out.println("\nInitializing Report Request");
                System.out.println("---------------------------");
            }

            Authenticator.setDefault(new ReportAuthenticator());

            // Generate parameter string from request
            String parameterString = "rs:Command=Render&rc:Toolbar=false";

            // Get the list of parameters that can be defined by the user.
            ArrayList availableParams = GetAvailableParameters.getParameters();

            Enumeration paramEnum = request.getParameterNames();

            String currentParam;
            while(paramEnum.hasMoreElements())
            {
                currentParam = (String)paramEnum.nextElement();
                if(availableParams.contains(currentParam))
                {
                    // If parameter is available, add it to the string.
                    parameterString += "&" + currentParam + "=" + request.getParameter(currentParam);
                }
            }

            String reportName = request.getParameter("reportName");

            if(DEBUG)
            {
                System.out.println("ReportRequest - Parameter String: " + parameterString);
                System.out.println("ReportRequest - Report retrieved: " + reportName);
            }

            if (reportName == null)
            {
                // Bail out if no report name is found.
                ServletOutputStream responseErrorStream = response.getOutputStream();
                responseErrorStream.println("ERROR: No report name specified");
                responseErrorStream.close();
                return;
            }

            // Establish HTTP POST connection to report server
            String urlString = REPORT_SERVER_URL + "?" + REPORT_PATH + reportName;
            URL url = new URL(urlString);

            HttpURLConnection repCon = (HttpURLConnection)url.openConnection();

            repCon.setRequestMethod("POST");
            repCon.setDoOutput(true);
            repCon.setUseCaches(false);
            repCon.setFollowRedirects(false);
            repCon.setRequestProperty("User-Agent", "Mozilla/5.0");
            repCon.setRequestProperty("Content-type", "application/x-www-form-urlencoded" );
            repCon.setRequestProperty("Content-length", Integer.toString(parameterString.length()));

            // Send parameter string to report server
            PrintWriter repOutStream = new PrintWriter(repCon.getOutputStream());

            repOutStream.println(parameterString);
            repOutStream.close();

            // Pipe Report Server's Output to the client
            forwardResponse(repCon, response);
        }
        catch (Exception e)
        {
            e.printStackTrace();

            // Alert the client there has been an error.
            ServletOutputStream responseErrorStream = response.getOutputStream();
            responseErrorStream.println("There has been an error.  Please check the system log for details.");
            responseErrorStream.close();
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Redirect HTTP GET requests to doPost.
        doPost(request, response);
    }

    private void forwardResponse(HttpURLConnection reportCon, HttpServletResponse clientResponse) throws ServletException, IOException
    {
        // Take the report server's response and forward it to the client.

        String cookie = reportCon.getHeaderField("Set-Cookie");

        if(cookie == null)
        {
            System.out.println("ReportRequest - ERROR: No cookie provided by report server.  Aborting.");
            return;
        }

        if(cookie.indexOf(";") != -1)
        {
            cookie = cookie.substring(0,cookie.indexOf(";"));
        }
        if(DEBUG)
        {
            System.out.println("ReportRequest - Cookie: " + cookie);
        }

        String contentType = reportCon.getContentType();

        clientResponse.setContentType(contentType);
        clientResponse.setHeader("Content-disposition", reportCon.getHeaderField("Content-disposition"));

        InputStream repInStream = reportCon.getInputStream();
        ServletOutputStream clientOutStream = clientResponse.getOutputStream();

        if(!contentType.equals("text/html"))
        {
            // Use a buffered stream to send all binary formats.
            BufferedInputStream bis = new BufferedInputStream(repInStream);
            BufferedOutputStream bos = new BufferedOutputStream(clientOutStream);

            byte[] buff = new byte[BUFFER_SIZE];
            int bytesRead;

            while(-1 != (bytesRead = bis.read(buff, 0, BUFFER_SIZE)))
            {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        }
        else
        {
            /*
             * Use a character stream to send HTML to the client, replacing
             * references to the reporting server with the GetReportItem
             * servlet.
             */

            String currentWindow = "";
            int itemsFound = 0;

            for(int ch;(ch = repInStream.read()) != -1;)
            {
                if(currentWindow.length() < REPORT_SERVER_URL.length())
                {
                    currentWindow += (char)ch;
                }
                else if(currentWindow.equalsIgnoreCase(REPORT_SERVER_URL) && (char)ch == '?')
                {
                    itemsFound++;

                    clientOutStream.print(REPORT_ITEM_SERVLET_URL + "?cookie=" + cookie + "&");
                    currentWindow = "";
                }
                else
                {
                    clientOutStream.print(currentWindow.charAt(0));
                    currentWindow = currentWindow.substring(1) + (char)ch;
                }
            }
            clientOutStream.print(currentWindow);

            if(DEBUG)
            {
                System.out.println("ReportRequest - " + itemsFound + " references to the report server found.");
            }
        }

        repInStream.close();
        clientOutStream.close();
    }
}

Create Java Classes named as :

 GetAvailableParameters and ReportAuthenticator

Structure: 1. util/ GetAvailableParameters

and 2. util/ ReportAuthenticator

In ReportAuthenticator  Class we need to provide the Credentials:

   private String username = "shekar";
    private String password = "Sana";

Thanks 

SANA




25 July, 2013

Shibboleth SP Installation Guide:


Shibboleth setup in Windows:
1. Pre Requiste Softwares Installation.
2. SP Installation.
3. SP Configuration.
4. IDP Installation.
5. IDP Configuration.

1) Pre Requiste Softwares Installation:

            1) Install JDK 1.6 and configure the JAVA_HOME path.

            2) Install the IIS on Windows XP, Vista, Except on Windows 7 -- as IIS will be available in Windows 7 by default.

            In case of Windows 7, IIS Services needs to be enabled.
            For enabling the IIS services,
Server Manager is not available in Windows 7. So we have to go to, Start-->Control Panel-->Programs-->Turn windows features on or off(Programs and Features). Expand all, Enable the IIS services & filters.
                       
            To Check whether the IIS is started or not
                        Start--> All programs--> Accessories--> Commandprompt--> Rightclick, run as Adminstrator-->type "iisreset"  should restart the iis server. Otherwise we didnt installed the IIS.

2. SP Installation:

             Install the SP by setting the installation path as c:\opt\shibboleth-sp
           
Check whether the shibboleth services are up or not.
                        Start--> run command--> type "services.msc"
                        shibboleth service should be up, otherwise reinstall it.

            Type -- http://127.0.0.1/Shibboleth.sso/Status
                        You should see a bundle of xml's.
                
 Else,
              1.If any errors on blacklist or whitelist line,  remove the blacklist or whitelist line based on the error from shibboleth2.xml
             

3. SP Configuration:

 Do the configurations, as per the section 2.5.

 Note:   Do the below change in the 13th Page,
  In the 4th point, Change the current one to the below one. ( Don't include the discoveryProtocol,discoveryURL attributes in <SSO> and Don't use the value SAML1. )

               <SSO entityID="https://shib-idp.umsystem.edu/idp/shibboleth">SAML2 </SSO>

check whether the sp is configured correctly or not by hitthing the url,

If the XML is downloaded properly, Configuration is correct.


 4. IDP Installation:


Install the IDP by setting the installation path as c:\opt\shibboleth-idp


5.IDP Configuration:

i)  Enable the MetaDataprovider in relying-party.xml and make the changes as below.

<metadata:MetadataProvider id="SPDOTNET" xsi:type="metadata:FileBackedHTTPMetadataProvider"
                          metadataURL="https://172.16.8.173/Shibboleth.sso/Metadata"
                          backingFile="C:\opt\shibboleth-idp\metadata\173dotnet-metadata.xml"/>
 
ii) set IDP_HOME to home directory of IDP (C:\opt\shibboleth-idp) in Environment Variables.
    
iii) Remove all the entries for authentication except "UsernamePassword" and "PreviousSession" in Login Handlers section  of handler.xml

iv) Add following for detail debug trace in logging.xml
<logger name="edu.internet2.middleware.shibboleth.common.attribute">
         <level value="DEBUG" />
</logger>


Sample Shibolth2.xml file:

<SPConfig xmlns="urn:mace:shibboleth:2.0:native:sp:config"
    xmlns:conf="urn:mace:shibboleth:2.0:native:sp:config"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"   
    xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
    clockSkew="180">

    <!--
    The InProcess section contains settings affecting web server modules.
    Required for IIS, but can be removed when using other web servers.
    -->
   

    <!--
    By default, in-memory StorageService, ReplayCache, ArtifactMap, and SessionCache
    are used. See example-shibboleth2.xml for samples of explicitly configuring them.
    -->

    <!--
    To customize behavior for specific resources on IIS, and to link vhosts or
    resources to ApplicationOverride settings below, use the XML syntax below.
    See https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPRequestMapHowTo for help.
   
    Apache users should rely on web server options/commands in most cases, and can remove the
    RequestMapper element. See https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig
    -->
    <RequestMapper type="Native">
        <RequestMap>
            <!--
            The example requires a session for documents in /secure on the containing host with http and
            https on the default ports. Note that the name and port in the <Host> elements MUST match
            Apache's ServerName and Port directives or the IIS Site name in the <ISAPI> element above.
            -->
            <Host name="sp.example.org">
                <Path name="secure" authType="shibboleth" requireSession="true"/>
            </Host>
            <!-- Example of a second vhost mapped to a different applicationId. -->
            <!--
            <Host name="admin.example.org" applicationId="admin" authType="shibboleth" requireSession="true"/>
            -->
        </RequestMap>
    </RequestMapper>

    <!--
    The ApplicationDefaults element is where most of Shibboleth's SAML bits are defined.
    Resource requests are mapped by the RequestMapper to an applicationId that
    points into to this section (or to the defaults here).
    -->
    <ApplicationDefaults entityID="https://xyz.com/shibboleth"
                         REMOTE_USER="eppn persistent-id targeted-id">

        <!--
        Controls session lifetimes, address checks, cookie handling, and the protocol handlers.
        You MUST supply an effectively unique handlerURL value for each of your applications.
        The value defaults to /Shibboleth.sso, and should be a relative path, with the SP computing
        a relative value based on the virtual host. Using handlerSSL="true", the default, will force
        the protocol to be https. You should also set cookieProps to "https" for SSL-only sites.
        Note that while we default checkAddress to "false", this has a negative impact on the
        security of your site. Stealing sessions via cookie theft is much easier with this disabled.
        -->
        <Sessions lifetime="28800" timeout="3600" relayState="ss:mem"
                  checkAddress="false" handlerSSL="false" cookieProps="http">

            <!--
            Configures SSO for a default IdP. To allow for >1 IdP, remove
            entityID property and adjust discoveryURL to point to discovery service.
            (Set discoveryProtocol to "WAYF" for legacy Shibboleth WAYF support.)
            You can also override entityID on /Login query string, or in RequestMap/htaccess.
            -->

           <!-- <SSO entityID="https://idp.example.org/idp/shibboleth"
                 discoveryProtocol="SAMLDS" discoveryURL="https://ds.example.org/DS/WAYF">
              SAML2 SAML1
            </SSO> -->

     <SSO entityID="https://facebook.com/sso/saml2/idp/metadata.php" ECP="true">
               SAML2
            </SSO>

            <!-- SAML and local-only logout. -->
            <Logout>SAML2 Local</Logout>

            <!-- Extension service that generates "approximate" metadata based on SP configuration. -->
            <Handler type="MetadataGenerator" Location="/Metadata" signing="false"/>

            <!-- Status reporting service. -->
            <Handler type="Status" Location="/Status" acl="127.0.0.1 ::1"/>

            <!-- Session diagnostic service. -->
            <Handler type="Session" Location="/Session" showAttributeValues="true"/>

            <!-- JSON feed of discovery information. -->
            <Handler type="DiscoveryFeed" Location="/DiscoFeed"/>
        </Sessions>

        <!--
        Allows overriding of error template information/filenames. You can
        also add attributes with values that can be plugged into the templates.
        -->
        <Errors supportContact="root@localhost"
            helpLocation="/about.html"
            styleSheet="/shibboleth-sp/main.css"/>
       
        <!-- Example of remotely supplied batch of signed metadata. -->
        <!--
        <MetadataProvider type="XML" uri="http://federation.org/federation-metadata.xml"
              backingFilePath="federation-metadata.xml" reloadInterval="7200">
            <MetadataFilter type="RequireValidUntil" maxValidityInterval="2419200"/>
            <MetadataFilter type="Signature" certificate="fedsigner.pem"/>
        </MetadataProvider>
        -->

        <!-- Example of locally maintained metadata. -->
        <!--
        <MetadataProvider type="XML" file="partner-metadata.xml"/>
        -->

    <MetadataProvider type="XML" uri="https:///facebook.com/sso/saml2/idp/metadata.php"
            backingFilePath="timetrack-metadata.xml" reloadInterval="7200">
       </MetadataProvider>


        <!-- Map to extract attributes from SAML assertions. -->
        <AttributeExtractor type="XML" validate="true" reloadChanges="false" path="attribute-map.xml"/>
       
        <!-- Use a SAML query if no attributes are supplied during SSO. -->
        <AttributeResolver type="Query" subjectMatch="true"/>

        <!-- Default filtering policy for recognized attributes, lets other data pass. -->
        <AttributeFilter type="XML" validate="true" path="attribute-policy.xml"/>

        <!-- Simple file-based resolver for using a single keypair. -->
       <!-- <CredentialResolver type="File" key="sp-key.pem" certificate="sp-cert.pem"/>-->

<CredentialResolver type="File" key="C:/opt/Apache2.2/conf/privatekey.key" certificate="C:/opt/Apache2.2/conf/pulse.photoninfotech.com.crt"/>

        <!--
        The default settings can be overridden by creating ApplicationOverride elements (see
        the https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApplicationOverride topic).
        Resource requests are mapped by web server commands, or the RequestMapper, to an
        applicationId setting.
       
        Example of a second application (for a second vhost) that has a different entityID.
        Resources on the vhost would map to an applicationId of "admin":
        -->
        <!--
        <ApplicationOverride id="admin" entityID="https://admin.example.org/shibboleth"/>
        -->
    </ApplicationDefaults>
   
    <!-- Policies that determine how to process and authenticate runtime messages. -->
    <SecurityPolicyProvider type="XML" validate="true" path="security-policy.xml"/>

    <!-- Low-level configuration about protocols and bindings available for use. -->
    <ProtocolProvider type="XML" validate="true" reloadChanges="false" path="protocols.xml"/>

</SPConfig>


Shibboleth:

       Shibboleth is a 'single-sign in', or logging-in system for computer networks and the Internet. It allows people to sign in, using just one 'identity', to various systems run by 'federations' of different organizations or institutions. The federations are often universities or public service organizations.
The Shibboleth Internet2 middleware initiative created an architecture and open-source implementation for identity management and federated identity-based authentication and authorization (or access control) infrastructure based on Security Assertion Markup Language (SAML). Federated identity allows for information about users in one security domain to be provided to other organizations in a federation. This allows for cross-domain single sign-on and removes the need for content providers to maintain user names and passwords. Identity providers (IdPs) supply user information, while service providers (SPs) consume this information and give access to secure content.

 Service Provider:

The Service Provider SSO-enables and Federation-enables web applications written with any programming language or framework; integrating natively with popular web servers such as Apache and IIS. A loosely coupled integration strategy allows you to support SAML, rich attribute-exchange, and many value-added features, often without significantly changing your application code or using proprietary interfaces.

The normal Service Provider process is:

    Intercept access to a protected resource or application entry point.
    Discover the user's choice of Identity Provider.
    Issue a SAML authentication request to the selected Identity Provider.
    Process the SAML authentication responses and extract rich user information.
    Apply local policies and gather additional data.
    Pass rich identity information to application resources.