7.5.2 ポートレット(index.jsp)

ポートレット(index.jsp)の作成を次に示します。

<%@ page contentType="text/html; charset=Shift_JIS" %>
<%@ taglib uri="http://cosminexus.com/admin/auth/uatags" prefix="ua" %>
<%@ page import="com.cosminexus.admin.auth.*" %>
<%@ page import="com.cosminexus.admin.auth.sso.callback.*" %>
<%@ page import="jp.co.hitachi.soft.portal.portlet.PortletUtils" %>
<%@ page import="javax.security.auth.*" %>
<%@ page import="javax.security.auth.login.*" %>
<%@ page import="java.security.*" %>
<%@ page import="java.util.Vector" %>
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%!

 class SessionListener implements HttpSessionBindingListener {
   LoginContext lc;
   SessionListener(LoginContext lc) { this.lc = lc; }
   public void valueBound(HttpSessionBindingEvent evt) { }
   public void valueUnbound(HttpSessionBindingEvent evt) {
     try {
       lc.logout();
     } catch (LoginException e) {
     }
   }
 }

%>
<%
 String sid;  // バックエンドセッションID
 String portletURL; // バックエンドポートレット用URL

 String ns = PortletUtils.getNamespace(request, response);
 Object isBackendLoggedIn = session.getAttribute(ns+"isLoggedIn");

 if (isBackendLoggedIn == null) { // 初回ログイン時(バックエンドにログイン)
   LoginContext lc = null;
   try {
     WebSSOHandler h =
       new WebSSOHandler(request, response, null);
     lc = new LoginContext("Web", h);
     lc.login();
   } catch (LoginException e) {
     out.println("Webへのログインに失敗しました。<br>");
     out.println("詳細 : " + e);
     return;
   } catch (Exception e) {
     out.println("Webへのログインで障害が発生しました。<br>");
     out.println("詳細 : " + e);
     return;
   }

   Subject subject = lc.getSubject();
   Principal principal = (Principal)subject.getPrincipals().iterator().next();
   Vector tmp = (Vector)subject.getPublicCredentials().iterator().next();
   sid = (String)tmp.get(0);  // セッションID
   portletURL = (String)tmp.get(1); // ポートレットURL

   session.setAttribute(ns+"sid", sid);
   session.setAttribute(ns+"portletURL", portletURL);

   session.setAttribute(ns+"isLoggedIn", new Object());
   session.setAttribute(ns+"logoutCB", new SessionListener(lc));
 } else {
   sid = (String)session.getAttribute(ns+"sid");
   portletURL = (String)session.getAttribute(ns+"portletURL");
 }

 // ポートレット用コンテンツ作成
 try {
   URL url = new URL(portletURL+";"+sid);

   HttpURLConnection conn = (HttpURLConnection)url.openConnection();
   //conn.setRequestProperty("Cookie", sid);
   BufferedReader in =
     new BufferedReader(new InputStreamReader(conn.getInputStream(),
                                             "JISAutoDetect"));
   int BUFLEN = 512;
   char[] buf = new char[BUFLEN];
   while (in.read(buf, 0, BUFLEN) > 0) {
     out.println(buf);
   }

   in.close();
   conn.disconnect();
   
 } catch (Exception e) {
   out.println("バックエンドアクセス時に障害が発生しました。<br>");
   out.println("詳細 : " + e);
 }
%>