OAuth单点登录

编辑
  • 文档创建者:susie
  • 浏览次数:2827次
  • 编辑次数:13次
  • 最近更新:KingSir 于 2019-07-10
  • 1. 描述

    OAuth协议为用户资源的授权提供了一个安全、开放而又简易的标准,OAuth的授权不会使第三方触及到用户的账号信息,因此较安全。此篇文档将介绍FineBI系统如何实现oauth单点登录。


    2. 实现原理


    通过过滤器拦截请求,期间通过oauth的认证过程,拿到user,实现FineReport的单点登录。


    3. 操作步骤


    3.1 引入第三方jar


    1)编译class引入的jar:

    首先编译器中需要导入FineReport的jar包,详细方法点击Eclipse中启动设计器

    接着需要导入外部jar,commons-httpclient-3.1.0.jarezmorph-1.0.6.jarjavax.servlet-api-3.1.0.jar、 json-lib-2.4-jdk15.jarmorph-1.1.1.jarorg.apache.oltu.oauth2.client-1.0.1.jar

    2)运行工程时引入的jar:

    引入方法,将上述jar放置到%FR_HOME%/webapps/webroot/WEB-INF/lib文件夹下,如下图:

    注:若为BI的工程则不需要commons-httpclient-3.1.0.jar



    3.2 新建web.xml

    由于10.0工程里没有web.xml了,所以直接新建web.xml,放到在%FR_HOME%/webapps/webroot/WEB-INF下,若已有web.xml,则加入下面的内容:

    完整web.xml内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 
       xmlns="http://java.sun.com/xml/ns/j2ee" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
       version="2.4"> 
    
      <display-name>Template WebApp</display-name>
      
        <mime-mapping>
      <extension>msi</extension>
      <mime-type>application/x-msi</mime-type>
      </mime-mapping>
    
     <filter>    
        <filter-name>FrFilter</filter-name>    
        <filter-class>com.fr.FrLoginFilter</filter-class>    
    </filter>    
    <filter-mapping>    
        <filter-name>FrFilter</filter-name>    
        <url-pattern>/decision</url-pattern>    
    </filter-mapping>  
    	
     <filter>    
        <filter-name>filter</filter-name>
        <filter-class>com.fr.myfilter</filter-class>
    </filter>    
    <filter-mapping>    
        <filter-name>filter</filter-name>
        <url-pattern>/decision</url-pattern>    
    </filter-mapping>  
    
    </web-app>


    3.3 编译class文件


    1)FrLoginFilter:

    package com.fr;
    
    import com.fr.decision.authority.data.User;
    import com.fr.decision.webservice.exception.user.UserNotExistException;
    import com.fr.decision.webservice.v10.login.LoginService;
    import com.fr.decision.webservice.v10.login.TokenResource;
    import com.fr.decision.webservice.v10.user.UserService;
    import com.fr.log.FineLoggerFactory;
    import com.fr.stable.StringUtils;
    import com.fr.web.utils.WebUtils;
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class FrLoginFilter implements Filter {
        public FrLoginFilter() {
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest)servletRequest;
            HttpServletResponse res = (HttpServletResponse)servletResponse;
            String username = WebUtils.getHTTPRequestParameter(req, "username");
    
            try {
                if (StringUtils.isNotEmpty(username)) {
                    FineLoggerFactory.getLogger().error("username:" + username);
                    User user = UserService.getInstance().getUserByUserName(username);
                    if (user == null) {
                        throw new UserNotExistException();
                    }
    
                    String oldToken = TokenResource.COOKIE.getToken(req);
                    if (oldToken == null) {
                        String token = LoginService.getInstance().login(req, res, username);
                        req.setAttribute("fine_auth_token", token);
                        filterChain.doFilter(req, res);
                    } else {
                        filterChain.doFilter(req, res);
                    }
                } else {
                    filterChain.doFilter(req, res);
                }
            } catch (Exception var10) {
                FineLoggerFactory.getLogger().error(var10.getMessage(), var10);
            }
    
        }
    
        public void destroy() {
        }
    }

    2)HttpUtil:

    package com.fr;
    
    import java.security.*;
    import javax.net.ssl.*;
    import com.fr.third.org.hsqldb.lib.*;
    import java.net.*;
    import java.io.*;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.HashMap;
    import java.util.Map;
    
    public class HttpUtil
    {
        private static final String DEFAULT_CHARSET = "UTF-8";
        private static final String METHOD_POST = "POST";
        private static final String METHOD_GET = "GET";
        private static final int CONNECTTIMEOUT = 5000;
        private static final int READTIMEOUT = 5000;
    
        private static class DefaultTrustManager implements X509TrustManager {
    
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    
            }
    
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
        private static HttpURLConnection getConnection(final URL url, final String method, final String ctype) throws IOException {
            HttpURLConnection conn = null;
            if ("https".equals(url.getProtocol())) {
                SSLContext ctx = null;
                try {
                    ctx = SSLContext.getInstance("TLS");
                    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
                }
                catch (Exception e) {
                    throw new IOException(e);
                }
                final HttpsURLConnection connHttps = (HttpsURLConnection)url.openConnection();
                connHttps.setSSLSocketFactory(ctx.getSocketFactory());
                connHttps.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
                conn = connHttps;
            }
            else {
                conn = (HttpURLConnection)url.openConnection();
            }
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("User-Agent", "quantangle- apiclient-java");
            conn.setRequestProperty("Content-Type", ctype);
            conn.setRequestProperty("Connection", "Keep-Alive");
            return conn;
        }
        
        public static String doGet(final String url, final Map<String, String> params) throws IOException {
            return doGet(url, params, "UTF-8");
        }
        
        public static String doGet(String url, final Map<String, String> params, final String charset) throws IOException {
            if (StringUtil.isEmpty(url) || params == null) {
                return null;
            }
            String response = "";
            url = url + "?" + buildQuery(params, charset);
            HttpURLConnection conn = null;
            final String ctype = "application/x-www-form- urlencoded;charset=" + charset;
            conn = getConnection(new URL(url), "GET", ctype);
            response = getResponseAsString(conn);
            return response;
        }
        
        public static String doPost(final String url, final Map<String, String> params) throws IOException {
            return doPost(url, params, 5000, 5000);
        }
        
        public static String doPost(final String url, final Map<String, String> params, final int connectTimeOut, final int readTimeOut) throws IOException {
            return doPost(url, params, "UTF-8", connectTimeOut, readTimeOut);
        }
        
        public static String doPost(final String url, final Map<String, String> params, final String charset, final int connectTimeOut, final int readTimeOut) throws IOException {
            HttpURLConnection conn = null;
            String response = "";
            final String ctype = "application/x-www-form- urlencoded;charset=" + charset;
            conn = getConnection(new URL(url), "POST", ctype);
            conn.setConnectTimeout(connectTimeOut);
            conn.setReadTimeout(readTimeOut);
            conn.getOutputStream().write(buildQuery(params, charset).getBytes(charset));
            response = getResponseAsString(conn);
            return response;
        }
        
        public static String buildQuery(final Map<String, String> params, final String charset) {
            if (params == null || params.isEmpty()) {
                return null;
            }
            final StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (final Map.Entry<String, String> entry : params.entrySet()) {
                if (first) {
                    first = false;
                }
                else {
                    sb.append("&");
                }
                final String key = entry.getKey();
                final String value = entry.getValue();
                if (!StringUtil.isEmpty(key) && !StringUtil.isEmpty(value)) {
                    try {
                        sb.append(key).append("=").append(URLEncoder.encode(value, charset));
                    }
                    catch (UnsupportedEncodingException ex) {}
                }
            }
            return sb.toString();
        }
        
        public static Map<String, String> splitQuery(final String query, final String charset) {
            final Map<String, String> ret = new HashMap<String, String>();
            if (!StringUtil.isEmpty(query)) {
                final String[] split2;
                final String[] splits = split2 = query.split("\\&");
                for (final String split : split2) {
                    final String[] keyAndValue = split.split("\\=");
                    boolean flag = true;
                    for (int i = 0, len = keyAndValue.length; i < len; ++i) {
                        if (StringUtil.isEmpty(keyAndValue[i])) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag && keyAndValue.length == 2) {
                        try {
                            ret.put(keyAndValue[0], URLDecoder.decode(keyAndValue[1], charset));
                        }
                        catch (UnsupportedEncodingException ex) {}
                    }
                }
            }
            return ret;
        }
        
        private static byte[] getTextEntry(final String fieldName, final String fieldValue, final String charset) throws IOException {
            final StringBuilder entry = new StringBuilder();
            entry.append("Content-Disposition:form-data;name=\"");
            entry.append(fieldName);
            entry.append("\"\r\nContent-Type:text/plain\r\n\r\n");
            entry.append(fieldValue);
            return entry.toString().getBytes(charset);
        }
        
        private static byte[] getFileEntry(final String fieldName, final String fileName, final String mimeType, final String charset) throws IOException {
            final StringBuilder entry = new StringBuilder();
            entry.append("Content-Disposition:form-data;name=\"");
            entry.append(fieldName);
            entry.append("\";filename=\"");
            entry.append(fileName);
            entry.append("\"\r\nContent-Type:");
            entry.append(mimeType);
            entry.append("\r\n\r\n");
            return entry.toString().getBytes(charset);
        }
        
        private static String getResponseAsString(final HttpURLConnection conn) throws IOException {
            final String charset = getResponseCharset(conn.getContentType());
            final InputStream es = conn.getErrorStream();
            if (es == null) {
                return getStreamAsString(conn.getInputStream(), charset);
            }
            final String msg = getStreamAsString(es, charset);
            if (StringUtil.isEmpty(msg)) {
                throw new IOException("{\"" + conn.getResponseCode() + "\":\"" + conn.getResponseMessage() + "\"}");
            }
            throw new IOException(msg);
        }
        
        private static String getStreamAsString(final InputStream input, final String charset) throws IOException {
            final StringBuilder sb = new StringBuilder();
            BufferedReader bf = null;
            try {
                bf = new BufferedReader(new InputStreamReader(input, charset));
                String str;
                while ((str = bf.readLine()) != null) {
                    sb.append(str);
                }
                return sb.toString();
            }
            finally {
                if (bf != null) {
                    bf.close();
                    bf = null;
                }
            }
        }
        
        private static String getResponseCharset(final String ctype) {
            String charset = "UTF-8";
            if (!StringUtil.isEmpty(ctype)) {
                final String[] split;
                final String[] params = split = ctype.split("\\;");
                for (String param : split) {
                    param = param.trim();
                    if (param.startsWith("charset")) {
                        final String[] pair = param.split("\\=");
                        if (pair.length == 2) {
                            charset = pair[1].trim();
                        }
                    }
                }
            }
            return charset;
        }
    }

    3)myexporter:

    package com.fr;
    
    import com.fr.base.DynamicUnitList;
    import com.fr.base.FRContext;
    import com.fr.base.ResultFormula;
    import com.fr.general.ComparatorUtils;
    import com.fr.general.DeclareRecordType;
    import com.fr.general.ModuleContext;
    import com.fr.io.TemplateWorkBookIO;
    import com.fr.io.exporter.AppExporter;
    import com.fr.io.exporter.PDFExporter;
    import com.fr.io.exporter.WordExporter;
    import com.fr.json.JSONArray;
    import com.fr.json.JSONException;
    import com.fr.json.JSONObject;
    import com.fr.main.TemplateWorkBook;
    import com.fr.main.workbook.ResultWorkBook;
    import com.fr.page.PageSetProvider;
    import com.fr.page.PaperSettingProvider;
    import com.fr.report.cell.CellElement;
    import com.fr.report.cell.DefaultTemplateCellElement;
    import com.fr.report.cell.ResultCellElement;
    import com.fr.report.cell.cellattr.PageExportCellElement;
    import com.fr.report.core.ReportUtils;
    import com.fr.report.core.block.PolyResultWorkSheet;
    import com.fr.report.module.EngineModule;
    import com.fr.report.worksheet.PageRWorkSheet;
    import com.fr.stable.CodeUtils;
    import com.fr.stable.ColumnRow;
    import com.fr.stable.CommonCodeUtils;
    import com.fr.stable.PageActor;
    import com.fr.stable.unit.FU;
    import com.fr.stable.unit.UNIT;
    import com.fr.web.Browser;
    import com.fr.web.core.ErrorHandlerHelper;
    import com.fr.web.core.utils.ExportUtils;
    import com.fr.web.utils.WebUtils;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class myexporter extends HttpServlet {
        private static boolean offlineWriteAble = true;
        private static final Pattern KEY_VALUE_PATTERN = Pattern.compile("[^{,}]*:[^{,}]*");
        private static final long serialVersionUID = 1L;
    
        public myexporter() {
        }
    
        public static void dealResponse4Export(HttpServletResponse res) {
            res.setHeader("Cache-Control", "public");
            res.setHeader("Cache-Control", "max-age=3");
            res.reset();
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    
        public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
            try {
                ModuleContext.startModule(EngineModule.class.getName());
                dealResponse4Export(res);
                String fileName = WebUtils.getHTTPRequestParameter(req, "__filename__");
                String format = WebUtils.getHTTPRequestParameter(req, "format");
                Browser browser = Browser.resolve(req);
                fileName = browser.getEncodedFileName4Download(fileName);
                List paraMapList = new ArrayList();
                List reportPathList = new ArrayList();
                PaperSettingProvider paperSettingProvider = null;
                if (WebUtils.getHTTPRequestParameter(req, "reportlets") != null) {
                    createReportsFromReportlets(WebUtils.getHTTPRequestParameter(req, "reportlets"), reportPathList, paraMapList);
                    ResultWorkBook[] resultWorkBook = new ResultWorkBook[reportPathList.size()];
                    PolyResultWorkSheet allInOneSheet = new PageRWorkSheet();
    
                    for (int i = 0; i < reportPathList.size(); ++i) {
                        TemplateWorkBook workbook = TemplateWorkBookIO.readTemplateWorkBook(String.valueOf(reportPathList.get(i)));
                        Map paraMap = (Map) paraMapList.get(i);
                        resultWorkBook[i] = workbook.execute(paraMap, new PageActor());
                        if (i == 0) {
                            paperSettingProvider = (PaperSettingProvider) ReportUtils.getPaperSettingListFromWorkBook(workbook).get(0);
                        }
                    }
    
                    int length = resultWorkBook.length;
                    long[] lengthx = new long[length];
                    long[] lengthy = (long[]) lengthx.clone();
                    if (length > 0) {
                        lengthx[0] = lengthy[0] = 0L;
                    }
    
                    for (int i = 1; i < length; ++i) {
                        long sumy = 0L;
    
                        for (int county = resultWorkBook[i - 1].getElementCaseReport(0).getRowCount(); county-- > 0; sumy += resultWorkBook[i - 1].getElementCaseReport(0).getRowHeight(county).getLen()) {
                            ;
                        }
    
                        lengthx[i] = 0L;
                        lengthy[i] = sumy + lengthy[i - 1];
                    }
    
                    ArrayList<UNIT> verticalList = new ArrayList();
                    ArrayList<UNIT> horizontalList = new ArrayList();
                    analyElementColumnRow(verticalList, horizontalList, resultWorkBook, lengthx, lengthy);
                    allInOneSheet = setNewColRowSize(verticalList, horizontalList, allInOneSheet);
                    allInOneSheet = fillBlankCell(verticalList.size(), horizontalList.size(), allInOneSheet);
                    int i = 0;
    
                    for (int len = reportPathList.size(); i < len; ++i) {
                        allInOneSheet = addElemToSheet(verticalList, horizontalList, allInOneSheet, resultWorkBook[i], lengthx[i], lengthy[i]);
                    }
    
                    if (paperSettingProvider == null) {
                        return;
                    }
    
                    doExport(req, res, format, fileName, false, browser, allInOneSheet.generateReportPageSet(paperSettingProvider));
                }
            } catch (Exception var24) {
                var24.printStackTrace();
            }
    
        }
    
        private static void doExport(HttpServletRequest req, HttpServletResponse res, String format, String fileName, boolean isEmbbed, Browser browser, PageSetProvider page) throws Exception {
            AppExporter[] exporters = new AppExporter[]{null};
            DeclareRecordType[] exportTypes = new DeclareRecordType[]{null};
            OutputStream outputStream = res.getOutputStream();
            getExporterAndTypeAndexport(req, res, format, fileName, isEmbbed, browser, exporters, exportTypes, outputStream, page);
            DeclareRecordType exportType = exportTypes[0];
            if (exportType == null) {
                ErrorHandlerHelper.getErrorHandler().error(req, res, "Cannot recognize the specifed export format:" + format + ",\nThe correct format can be PDF,Excel,Word,SVG,CSV,Text or Image.");
            } else {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException var12) {
                    ;
                }
    
            }
        }
    
        private static void getExporterAndTypeAndexport(HttpServletRequest req, HttpServletResponse res, String format, String fileName, boolean isEmbbed, Browser browser, AppExporter[] exporters, DeclareRecordType[] exportTypes, OutputStream out, PageSetProvider page) throws Exception {
            if (format.equalsIgnoreCase("PDF")) {
                ExportUtils.setPDFContent(res, fileName, isEmbbed);
                PDFExporter PDFExport = new PDFExporter();
                PDFExport.export(out, page);
            } else if (format.equalsIgnoreCase("Word")) {
                ExportUtils.setWordConetent(res, fileName);
                WordExporter WordExport = new WordExporter();
                WordExport.export(out, page);
            }
    
        }
    
        public static PolyResultWorkSheet fillBlankCell(int rowCount, int colCount, PolyResultWorkSheet allInOneSheet) {
            for (int i = 0; i < rowCount; ++i) {
                for (int j = 0; j < colCount; ++j) {
                    ResultCellElement ce = createDefaultCellElement(j, i);
                    allInOneSheet.addCellElement(ce);
                }
            }
    
            allInOneSheet.setRowMappingArray(new int[0]);
            allInOneSheet.setColumnMappingArray(new int[0]);
            return allInOneSheet;
        }
    
        public static ResultCellElement createDefaultCellElement(int col, int row) {
            return new PageExportCellElement(new DefaultTemplateCellElement(col, row));
        }
    
        public static PolyResultWorkSheet addElemToSheet(ArrayList<UNIT> verticalList, ArrayList<UNIT> horizontalList, PolyResultWorkSheet page_sheet, ResultWorkBook resultWorkBook, long lengthx, long lengthy) {
            UNIT x = FU.getInstance(lengthx);
            UNIT y = FU.getInstance(lengthy);
            DynamicUnitList newRowList = page_sheet.getRowHeightList_DEC();
            DynamicUnitList newColList = page_sheet.getColumnWidthList_DEC();
            int rowCount = page_sheet.getRowCount();
            int colCount = page_sheet.getColumnCount();
            DynamicUnitList rowHeightList = resultWorkBook.getElementCaseReport(0).getRowHeightList_DEC();
            DynamicUnitList colWidthList = resultWorkBook.getElementCaseReport(0).getColumnWidthList_DEC();
            Iterator<CellElement> it = resultWorkBook.getElementCaseReport(0).cellIterator();
            HashMap<String, String> columnRowMap = new HashMap();
            HashMap formulaMap = new HashMap();
    
            while (it.hasNext()) {
                CellElement ce = (CellElement) it.next();
                UNIT ceX = x.add(colWidthList.getRangeValueFromZero(ce.getColumn()));
                UNIT ceWidth = colWidthList.getRangeValue(ce.getColumn(), ce.getColumn() + ce.getColumnSpan());
                UNIT ceY = y.add(rowHeightList.getRangeValueFromZero(ce.getRow()));
                UNIT ceHeight = rowHeightList.getRangeValue(ce.getRow(), ce.getRow() + ce.getRowSpan());
                int newCeCol = horizontalList.indexOf(ceX) + 1;
                int newCeColSpan = getNewSpan(newCeCol, newColList, ceWidth, colCount);
                int newCeRow = verticalList.indexOf(ceY) + 1;
                int newCeRowSpan = getNewSpan(newCeRow, newRowList, ceHeight, rowCount);
                ColumnRow oriCR = ColumnRow.valueOf(ce.getColumn(), ce.getRow());
                ColumnRow newCR = ColumnRow.valueOf(newCeCol, newCeRow);
                columnRowMap.put(oriCR.toString(), newCR.toString());
                ResultCellElement newCe = (ResultCellElement) ce.deriveCellElement(newCeCol, newCeRow, newCeColSpan, newCeRowSpan);
                page_sheet.addCellElement(newCe);
                if (ce.getValue() instanceof ResultFormula) {
                    formulaMap.put(newCe, (ResultFormula) ce.getValue());
                }
            }
    
            modifyAllFormula(formulaMap, columnRowMap);
            return page_sheet;
        }
    
        public static int getNewSpan(int newCeColRow, DynamicUnitList newColRowList, UNIT ceWidthHeight, int count) {
            for (int i = newCeColRow; i < count + 1; ++i) {
                if (ComparatorUtils.equals(ceWidthHeight, newColRowList.getRangeValue(newCeColRow, i))) {
                    return i - newCeColRow;
                }
            }
    
            return 0;
        }
    
        public static PolyResultWorkSheet setNewColRowSize(ArrayList<UNIT> verticalList, ArrayList<UNIT> horizontalList, PolyResultWorkSheet allInOneSheet) {
            int i;
            Object lastCoordinate;
            FU colWidth;
            for (i = 0; i < verticalList.size(); ++i) {
                lastCoordinate = i == 0 ? UNIT.ZERO : (UNIT) verticalList.get(i - 1);
                colWidth = ((UNIT) verticalList.get(i)).subtract((UNIT) lastCoordinate);
                allInOneSheet.setRowHeight(i, colWidth);
            }
    
            for (i = 0; i < horizontalList.size(); ++i) {
                lastCoordinate = i == 0 ? UNIT.ZERO : (UNIT) horizontalList.get(i - 1);
                colWidth = ((UNIT) horizontalList.get(i)).subtract((UNIT) lastCoordinate);
                allInOneSheet.setColumnWidth(i, colWidth);
            }
    
            return allInOneSheet;
        }
    
        public static void analyElementColumnRow(ArrayList<UNIT> verticalList, ArrayList<UNIT> horizontalList, ResultWorkBook[] resultWorkBooks, long[] lengthx, long[] lengthy) {
            int length = resultWorkBooks.length;
    
            for (int i = 0; i < length; ++i) {
                ResultWorkBook resultWorkBook = resultWorkBooks[i];
                UNIT y = FU.getInstance(lengthy[i]);
                int rowCount = resultWorkBook.getElementCaseReport(0).getRowCount();
                DynamicUnitList rowHeightList = resultWorkBook.getElementCaseReport(0).getRowHeightList_DEC();
                analyColumnRow(y, verticalList, rowHeightList, rowCount);
                UNIT x = FU.getInstance(lengthx[i]);
                int colCount = resultWorkBook.getElementCaseReport(0).getColumnCount();
                DynamicUnitList colWidthList = resultWorkBook.getElementCaseReport(0).getColumnWidthList_DEC();
                analyColumnRow(x, horizontalList, colWidthList, colCount);
            }
    
            sort(verticalList, horizontalList);
        }
    
        public static void analyColumnRow(UNIT startPoint, ArrayList<UNIT> verticalSet, DynamicUnitList rowHeightList, int count) {
            verticalSet.add(startPoint);
    
            for (int i = 0; i < count; ++i) {
                UNIT rowHeight = rowHeightList.getRangeValueFromZero(i + 1);
                UNIT rowY = rowHeight.add(startPoint);
                verticalSet.add(rowY);
            }
    
        }
    
        public static void sort(ArrayList<UNIT> verticalList, ArrayList<UNIT> horizontalList) {
            Comparator<UNIT> compare = new Comparator<UNIT>() {
                public int compare(UNIT o1, UNIT o2) {
                    if (o1.subtract(o2).equal_zero()) {
                        return 0;
                    }
                    return o1.subtract(o2).more_than_zero() ? 1 : -1;
                }
            };
            Collections.sort(verticalList, compare);
            Collections.sort(horizontalList, compare);
        }
    
        private static void modifyAllFormula(HashMap<CellElement, ResultFormula> formulaMap, HashMap<String, String> columnRowMap) {
            Iterator formulaIt = formulaMap.entrySet().iterator();
    
            while (formulaIt.hasNext()) {
                Entry<CellElement, ResultFormula> entry = (Entry) formulaIt.next();
                CellElement ce = (CellElement) entry.getKey();
                ResultFormula formula = (ResultFormula) entry.getValue();
                String content = formula.getTransferContent();
                Iterator crIt = columnRowMap.entrySet().iterator();
    
                while (crIt.hasNext()) {
                    Entry<String, String> crEntry = (Entry) crIt.next();
                    String oriCR = (String) crEntry.getKey();
                    String newCR = (String) crEntry.getValue();
                    if (content.indexOf(oriCR) != -1) {
                        content = getNewFormula(content, oriCR, newCR);
                        formula.setTransferContent(content);
                        ce.setValue(formula);
                    }
                }
            }
    
        }
    
        public static String getNewFormula(String formulaContent, String oriCR, String newCR) {
            String[] array = formulaContent.toUpperCase().split(oriCR);
            StringBuffer sb = new StringBuffer();
            int i = 0;
    
            for (int len = array.length; i < len; ++i) {
                sb.append(array[i]);
                if (formulaContent.endsWith(oriCR) || i != len - 1) {
                    String nodeCR = getNewColumnRow(array[i], i + 1, array, oriCR, newCR);
                    sb.append(nodeCR);
                }
            }
    
            return sb.toString();
        }
    
        private static String getNewColumnRow(String formulaPart, int nextIdx, String[] array, String oriCR, String newCR) {
            if (formulaPart.endsWith("$")) {
                return oriCR;
            } else {
                return nextIdx < array.length && startsWithDigit(array[nextIdx]) ? oriCR : newCR;
            }
        }
    
        private static boolean startsWithDigit(String s) {
            return Pattern.compile("^[0-9]").matcher(s.trim()).find();
        }
    
        public static String transferReportletsInfo(String reportletsInfo) {
            try {
                reportletsInfo = CodeUtils.cjkDecode(reportletsInfo.trim());
            } catch (Exception var2) {
                ;
            }
    
            String jsonString = null;
            if (reportletsInfo.length() > 0 && reportletsInfo.charAt(0) == '(') {
                jsonString = transferToJSONString(reportletsInfo);
            } else {
                jsonString = reportletsInfo;
            }
    
            return jsonString;
        }
    
        public static String transferToJSONString(String reportletsInfo) {
            if (reportletsInfo == null) {
                return null;
            } else {
                reportletsInfo = reportletsInfo.trim();
                if (reportletsInfo.length() <= 0) {
                    return null;
                } else {
                    reportletsInfo = reportletsInfo.substring(1, reportletsInfo.length() - 1);
                    StringBuffer rpSB = new StringBuffer("[");
                    Matcher matcher = KEY_VALUE_PATTERN.matcher(reportletsInfo);
                    int start = 0;
                    boolean var4 = false;
    
                    while (matcher.find()) {
                        int end = matcher.start();
                        String tmpText = reportletsInfo.substring(start, end);
                        if (tmpText != null && tmpText.length() > 0) {
                            rpSB.append(tmpText);
                        }
    
                        start = matcher.end();
                        String tmpStr = matcher.group();
                        String[] tmpStrs = tmpStr.split(":");
                        if (tmpStrs.length != 2) {
                            rpSB.append(tmpStr);
                        } else {
                            rpSB.append(tmpStrs[0]).append(':').append(quote(tmpStrs[1]));
                        }
                    }
    
                    rpSB.append(reportletsInfo.substring(start, reportletsInfo.length()));
                    rpSB.append(']');
                    return rpSB.toString();
                }
            }
        }
    
        private static String quote(String v) {
            return "\"" + CommonCodeUtils.javascriptEncode(v) + "\"";
        }
    
        public static void createReportsFromReportlets(String reportletsInfo, List reportPathList, List paraMapList) {
            reportPathList.clear();
            paraMapList.clear();
            if (reportletsInfo != null) {
                String jsonString = transferReportletsInfo(reportletsInfo);
                FRContext.getLogger().info("reportletsInfo:" + jsonString);
                if (jsonString != null) {
                    createFromReportlets(jsonString, reportPathList, paraMapList);
                }
            }
        }
    
        private static void createFromReportlets(String jsonString, List reportPathList, List paraMapList) {
            try {
                JSONArray reportlets = new JSONArray(jsonString);
    
                for (int i = 0; i < reportlets.length(); ++i) {
                    Map paraMap = new HashMap();
                    JSONObject jsonObject = reportlets.getJSONObject(i);
                    Iterator keys = jsonObject.keys();
    
                    while (keys.hasNext()) {
                        String key = (String) keys.next();
                        Object value = jsonObject.get(key);
                        value = value instanceof String ? CodeUtils.decodeText(String.valueOf(value)) : value;
                        paraMap.put(key, value);
                    }
    
                    String reportletPath = (String) paraMap.get("reportlet");
                    if (reportletPath != null) {
                        try {
                            reportPathList.add(reportletPath);
                            paraMapList.add(paraMap);
                        } catch (Exception var11) {
                            FRContext.getLogger().error(var11.getMessage(), var11);
                        }
                    }
                }
            } catch (JSONException var12) {
                FRContext.getLogger().error(var12.getMessage(), var12);
            }
    
        }
    }

    4)SSLConnectionClient:

    package com.fr;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import java.security.SecureRandom;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.KeyManager;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    import org.apache.oltu.oauth2.client.HttpClient;
    import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
    import org.apache.oltu.oauth2.client.response.OAuthClientResponse;
    import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory;
    import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
    import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
    import org.apache.oltu.oauth2.common.utils.OAuthUtils;
    
    public class SSLConnectionClient implements HttpClient {
        public SSLConnectionClient() {
        }
    
        public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
            String responseBody = null;
            URLConnection c = null;
            boolean var7 = false;
    
            int responseCode;
            try {
                URL url = new URL(request.getLocationUri());
                c = url.openConnection();
                responseCode = -1;
                if (c instanceof HttpsURLConnection) {
                    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) c;
                    SSLContext sslContext = SSLContext.getInstance("TLS");
                    sslContext.init((KeyManager[]) null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
                    httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
                    httpsURLConnection.setHostnameVerifier(new TrustAnyHostnameVerifier());
                    if (headers != null && !headers.isEmpty()) {
                        Iterator var11 = headers.entrySet().iterator();
    
                        while (var11.hasNext()) {
                            Entry<String, String> header = (Entry) var11.next();
                            httpsURLConnection.addRequestProperty((String) header.getKey(), (String) header.getValue());
                        }
                    }
    
                    if (!OAuthUtils.isEmpty(requestMethod)) {
                        httpsURLConnection.setRequestMethod(requestMethod);
                        if (requestMethod.equals("POST")) {
                            httpsURLConnection.setDoOutput(true);
                            OutputStream ost = httpsURLConnection.getOutputStream();
                            PrintWriter pw = new PrintWriter(ost);
                            pw.print(request.getBody());
                            pw.flush();
                            pw.close();
                        }
                    } else {
                        httpsURLConnection.setRequestMethod("GET");
                    }
    
                    httpsURLConnection.connect();
                    responseCode = httpsURLConnection.getResponseCode();
                    InputStream inputStream;
                    if (responseCode == 400) {
                        inputStream = httpsURLConnection.getErrorStream();
                    } else {
                        inputStream = httpsURLConnection.getInputStream();
                    }
    
                    responseBody = OAuthUtils.saveStreamAsString(inputStream);
                }
            } catch (Exception var13) {
                throw new OAuthSystemException(var13);
            }
    
            return OAuthClientResponseFactory.createCustomResponse(responseBody, c.getContentType(), responseCode, responseClass);
        }
    
        public void shutdown() {
        }
    
        static class TrustAnyTrustManager implements X509TrustManager {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
    
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
    
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }
        }
    
        static class TrustAnyHostnameVerifier implements HostnameVerifier {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }
    }

    5)myfilter,修改其中的tokenLocation和redirectURI为自身的地址:

    package com.fr;
    
    import com.fr.decision.webservice.v10.login.LoginService;
    import com.fr.json.JSONException;
    import net.sf.json.JSONObject;
    import com.fr.stable.StringUtils;
    import com.fr.web.utils.WebUtils;
    import java.io.IOException;
    import java.util.Set;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.oltu.oauth2.client.response.OAuthAuthzResponse;
    import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
    import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
    
    public class myfilter implements Filter {
        public myfilter() {
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest)request;
            HttpServletResponse res = (HttpServletResponse)response;
            OAuthAuthzResponse oAuthResponse = null;
            HttpSession session = req.getSession(true);
            String tokenLocation = "https:/www.example.com/oauth/token";
            String redirectURI = "http://localhost:8075/webroot/decision";
            String clientId = "dzs.hotelbi.local";
            String clientSecret = "da3e9b941b6dc724847c8426a323ddc8";
            String code = WebUtils.getHTTPRequestParameter(req, "code");
            System.out.println("code:" + code);
            String Token = "";
    
            try {
                if (!StringUtils.isEmpty(code)) {
                    oAuthResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(req);
                    System.out.println("oAuthResponse.getCode()=" + oAuthResponse.getCode());
    
    
                    JSONObject jsonParams = new JSONObject();
                    jsonParams.put("client_id", clientId);
                    jsonParams.put("client_secret", clientSecret);
                    jsonParams.put("redirect_uri", redirectURI);
                    jsonParams.put("code", oAuthResponse.getCode());
                    jsonParams.put("grant_type", "authorization_code");
                    // 通过接收到的授权码到SSO站点申请令牌
                    String returnParams = postByJsonParameters(tokenLocation, jsonParams);
    
                    JSONObject jsonResponse = new JSONObject();
                    jsonResponse = jsonResponse.fromObject(returnParams);
                    String accessToken = jsonResponse.getString("access_token");
    
                    System.out.println("Token" + accessToken);
    
                    JSONObject jsonParams1 = new JSONObject();
                    jsonParams1.put("access_token", accessToken);
                    String result = postByJsonParameters("https://oauth.shu.edu.cn/rest/user/getLoggedInUser", jsonParams1);
                    System.out.println("result = " + result);
                    String username = "";
                    if (!StringUtils.isEmpty(result)) {
                        JSONObject json = new JSONObject();
                        json = json.fromObject(result);
                        username = json.getString("username");
                        System.out.println("username" + username);
                    }
    
                    if (StringUtils.isNotEmpty(username)) {
                        String token = LoginService.getInstance().login(req, res, username);
                        req.setAttribute("fine_auth_token", token);
                    }
                    res.addCookie(new Cookie("access_token", Token));
                    filterChain.doFilter(req, res);
                } else {
                    System.out.println("code is empty!");
                }
            } catch (OAuthProblemException var20) {
                var20.printStackTrace();
            } catch (OAuthSystemException var21) {
                var21.printStackTrace();
            } catch (JSONException var22) {
                var22.printStackTrace();
            } catch (Exception var23) {
                var23.printStackTrace();
            }
    
        }
        /**
         * 模拟post请求方法,请求参数为json
         *
         * @param url
         * @param params
         * @return
         */
        public static String postByJsonParameters(String url, JSONObject params) {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            Set<String> keySet = params.keySet();
            try {
                NameValuePair[] postData = new NameValuePair[keySet.size()];
                int postDataIndex = 0;
                for (String key : keySet) {
                    postData[postDataIndex++] = new NameValuePair(key, params.getString(key));
                }
                postMethod.getParams().setContentCharset("UTF-8");
                postMethod.addParameters(postData);
    
                httpClient.executeMethod(postMethod);
                if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
                    String response = new String(postMethod.getResponseBodyAsString());
                    return response;
                } else {
                    return null;
                }
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                postMethod.releaseConnection();
            }
            return null;
        }
        public void destroy() {
        }
    }

    编译器中编译生成class文件,将其放入%FR_HOME%/webapps/webroot/WEB-INF/classes/com/fr目录下,若没有,则在对应目录下新建文件夹即可。




    3.4 查看效果


    重启报表工程,访问地址:

    https://www.example.com/oauth/authorize?response_type=code&scope=read&client_id=dzs.hotelbi.local&redirect_uri=http://localhost:8075/webroot/decision&scope=1&state=9441904a455e4123b3fd3ef51f1e262e

    进行登录,其中上述地址可根据自身在第三步骤输入的tokenLocation和redirectURI进行修改访问。

    传递参数的含义:

    Parameter 
    Name  
    Type    Description
      client_id    string  必须参数,在 OAuth 注册应用时获得的 API 
    Key。
      response_type  string  必须参数,此值固定为“code”。
      redirect_uri  string必须参数,授权后要回调的 UR I,当前系统通过
    此地址来获取 Code。  
      scope   string  非必须参数,以空格分隔的权限列表,若不传递
    此参数,代表请求用户的默认权限


    附件列表


    主题: 部署集成
    标签: 暂无标签 编辑/添加标签
    如果您认为本文档还有待完善,请编辑

    文档内容仅供参考,如果你需要获取更多帮助,付费/准付费客户请咨询帆软技术支持
    关于技术问题,您还可以前往帆软社区,点击顶部搜索框旁边的提问按钮
    若您还有其他非技术类问题,可以联系帆软传说哥(qq:1745114201

    此页面有帮助吗?只是浏览 [ 去社区提问 ]