Example usage for java.util.logging Level FINER

List of usage examples for java.util.logging Level FINER

Introduction

In this page you can find the example usage for java.util.logging Level FINER.

Prototype

Level FINER

To view the source code for java.util.logging Level FINER.

Click Source Link

Document

FINER indicates a fairly detailed tracing message.

Usage

From source file:com.npower.dm.server.session.ManagementSessionHandler.java

/**
 * Checks if the given command is splittable with the given sizeAvailable.
 *
 * @param cmd AbstractCommand//from ww  w. j a  v  a 2s  .co  m
 * @param sizeAvailable long
 * @return boolean
 */
private boolean checkForSplitData(AbstractCommand cmd, long sizeAvailable) {
    Item itemToSplit = null;
    //
    // If cmd contains no items or more than 1 items, no large object are permitted
    //
    if (cmd instanceof ItemizedCommand) {
        if (((ItemizedCommand) cmd).getItems().size() != 1) {
            if (log.isLoggable(Level.FINER)) {
                log.finer("Command with more items isn't splittable");
            }
            return false;
        } else {
            itemToSplit = (Item) ((ItemizedCommand) cmd).getItems().get(0);
        }
    } else {
        if (log.isLoggable(Level.FINER)) {
            log.finer("Command isn't a ItemizedCommand then it isn't splittable");
        }
        return false;
    }

    Data data = itemToSplit.getData();
    if (data == null) {
        return false;
    }
    String dataValue = data.getData();
    if (dataValue == null) {
        return false;
    }

    Object dataToSplit = dataValue;
    boolean isBinaryData = false;
    int lengthDataToSplit = 0;

    Meta meta = itemToSplit.getMeta();
    if (Constants.MIMETYPE_SYNCMLDM_WBXML.equals(mimeType)
            || Constants.MIMETYPE_SYNCMLDS_WBXML.equals(mimeType)) {

        if (meta != null) {
            String format = meta.getFormat();
            if (format != null && format.equalsIgnoreCase("b64")) {
                isBinaryData = true;
                dataToSplit = Base64.decode(((String) dataToSplit).getBytes());
                lengthDataToSplit = ((byte[]) dataToSplit).length;
            }

        }
    }

    if (!isBinaryData) {
        lengthDataToSplit = ((String) dataToSplit).length();
    }

    long maxObjSize = sessionState.getMaxObjSize();
    if (maxObjSize != 0 && lengthDataToSplit > maxObjSize) {
        if (log.isLoggable(Level.FINER)) {
            log.finer("The dimension of the data is greater of the maxObjSize");
        }
        // data too large
        return false;
    }
    //
    // try to split the cmd
    //
    if (sessionState.getNextDataToSend() == dataValue) {
        //
        // the item already has been splitted,
        // then no meta size is set
        //
    } else {
        //
        // We add data lenght information on the item
        //
        if (meta == null) {
            meta = new Meta();
            itemToSplit.setMeta(meta);
        }

        meta.setSize(new Long(lengthDataToSplit));
    }

    int sizeAvailableForData = calculateDataSizeAvailable(sizeAvailable, cmd, itemToSplit);

    if (sizeAvailableForData <= 0) {
        //
        // No space for data
        //
        return false;
    }

    sessionState.setSplittedCommand(cmd);

    Object newData = null;
    @SuppressWarnings("unused")
    int lengthNewData = 0;

    if (isBinaryData) {
        if (sizeAvailableForData > lengthDataToSplit) {
            // send all
            sizeAvailableForData = lengthDataToSplit;
            newData = dataToSplit;
        } else {
            newData = new byte[sizeAvailableForData];
            System.arraycopy(dataToSplit, 0, newData, 0, sizeAvailableForData);
        }
        lengthNewData = sizeAvailableForData;
    } else {
        newData = ((String) dataToSplit).substring(0, sizeAvailableForData);
        lengthNewData = ((String) newData).length();
    }

    if (isBinaryData) {
        newData = new String(Base64.encode((byte[]) newData));
    }
    itemToSplit.getData().setData((String) newData);

    if (sizeAvailableForData >= lengthDataToSplit) {
        // all data is sent
        sessionState.setNextDataToSend(null);
        itemToSplit.setMoreData(Boolean.FALSE);
    } else {
        //
        // We must save the data not sent
        //
        String dataNotSent = null;
        if (isBinaryData) {
            byte[] byteNotSent = new byte[lengthDataToSplit - sizeAvailableForData];
            System.arraycopy(dataToSplit, sizeAvailableForData, byteNotSent, 0,
                    lengthDataToSplit - sizeAvailableForData);
            dataNotSent = new String(Base64.encode(byteNotSent));
        } else {
            dataNotSent = ((String) dataToSplit).substring(sizeAvailableForData);

        }
        itemToSplit.setMoreData(Boolean.TRUE);
        sessionState.setNextDataToSend(dataNotSent);
    }

    return true;
}

From source file:foodsimulationmodel.pathmapping.Route.java

/**
 * /*from   www  . ja va 2  s .c o  m*/
 * @param c
 * @return
 * @throws Exception
 */
public Coordinate get(Coordinate c) throws Exception {
    if (c == null) {
        throw new Exception("Route.NearestRoadCoordCache.get() error: the given coordinate is null.");
    }
    double time = System.nanoTime();
    Coordinate nearestCoord = this.theCache.get(c);
    if (nearestCoord != null) {
        LOGGER.log(Level.FINER, "NearestRoadCoordCache.get() (using cache) - ("
                + (0.000001 * (System.nanoTime() - time)) + "ms)");
        return nearestCoord;
    }
    // If get here then the coord is not in the cache, agent not starting their journey from a house, search for
    // it manually. Search all roads in the vicinity, looking for the point which is nearest the person
    double minDist = Double.MAX_VALUE;
    Coordinate nearestPoint = null;
    Point coordGeom = this.geomFac.createPoint(c);

    // Note: could use an expanding envelope that starts small and gets bigger
    double bufferDist = GlobalVars.GEOGRAPHY_PARAMS.BUFFER_DISTANCE.LARGE.dist;
    double bufferMultiplier = 1.0;
    Envelope searchEnvelope = coordGeom.buffer(bufferDist * bufferMultiplier).getEnvelopeInternal();
    StringBuilder debug = new StringBuilder(); // incase the operation fails

    for (Road r : ContextManager.roadProjection.getObjectsWithin(searchEnvelope)) {

        DistanceOp distOp = new DistanceOp(coordGeom, ContextManager.roadProjection.getGeometry(r));
        double thisDist = distOp.distance();
        // BUG?: if an agent is on a really long road, the long road will not be found by getObjectsWithin because
        // it is not within the buffer
        debug.append("\troad ").append(r.toString()).append(" is ").append(thisDist)
                .append(" distance away (at closest point). ");

        if (thisDist < minDist) {
            minDist = thisDist;
            Coordinate[] closestPoints = distOp.closestPoints();
            // Two coordinates returned by closestPoints(), need to find the
            // one which isn''t the coord parameter
            debug.append("Closest points (").append(closestPoints.length).append(") are: ")
                    .append(Arrays.toString(closestPoints));
            nearestPoint = (c.equals(closestPoints[0])) ? closestPoints[1] : closestPoints[0];
            debug.append("Nearest point is ").append(nearestPoint.toString());
            nearestPoint = (c.equals(closestPoints[0])) ? closestPoints[1] : closestPoints[0];
        } // if thisDist < minDist
        debug.append("\n");

    } // for nearRoads

    if (nearestPoint != null) {
        LOGGER.log(Level.FINER, "NearestRoadCoordCache.get() (not using cache) - ("
                + (0.000001 * (System.nanoTime() - time)) + "ms)");
        return nearestPoint;
    }
    /* IF HERE THEN ERROR, PRINT DEBUGGING INFO */
    StringBuilder debugIntro = new StringBuilder(); // Some extra info for debugging
    debugIntro.append("Route.NearestRoadCoordCache.get() error: couldn't find a coordinate to return.\n");
    Iterable<Road> roads = ContextManager.roadProjection.getObjectsWithin(searchEnvelope);
    debugIntro.append("Looking for nearest road coordinate around ").append(c.toString()).append(".\n");
    debugIntro.append("RoadEnvironment.getObjectsWithin() returned ")
            .append(ContextManager.sizeOfIterable(roads) + " roads, printing debugging info:\n");
    debugIntro.append(debug);
    throw new Exception(debugIntro.toString());

}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReader.java

private DecodedDateTime decodeDateTimeData(String storageType, String FormatType, String rawDatum)
        throws IOException {

    if (dbgLog.isLoggable(Level.FINER))
        dbgLog.finer("(storageType, FormatType, rawDatum)=(" + storageType + ", " + FormatType + ", " + rawDatum
                + ")");
    /*//  w w w . j  a  v  a 2 s. co m
     *         Historical note:
           pseudofunctions,  td(), tw(), tm(), tq(), and th()
        used to be called     d(),  w(),  m(),  q(), and  h().
        Those names still work but are considered anachronisms.
            
    */

    long milliSeconds;
    String decodedDateTime = null;
    String format = null;

    if (FormatType.matches("^%tc.*")) {
        // tc is a relatively new format
        // datum is millisecond-wise

        milliSeconds = Long.parseLong(rawDatum) + STATA_BIAS_TO_EPOCH;
        decodedDateTime = sdf_ymdhmsS.format(new Date(milliSeconds));
        format = sdf_ymdhmsS.toPattern();
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("tc: result=" + decodedDateTime + ", format = " + format);

    } else if (FormatType.matches("^%t?d.*")) {
        milliSeconds = Long.parseLong(rawDatum) * MILLISECONDS_PER_DAY + STATA_BIAS_TO_EPOCH;
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("milliSeconds=" + milliSeconds);

        decodedDateTime = sdf_ymd.format(new Date(milliSeconds));
        format = sdf_ymd.toPattern();
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("td:" + decodedDateTime + ", format = " + format);

    } else if (FormatType.matches("^%t?w.*")) {

        long weekYears = Long.parseLong(rawDatum);
        long left = Math.abs(weekYears) % 52L;
        long years;
        if (weekYears < 0L) {
            left = 52L - left;
            if (left == 52L) {
                left = 0L;
            }
            //out.println("left="+left);
            years = (Math.abs(weekYears) - 1) / 52L + 1L;
            years *= -1L;
        } else {
            years = weekYears / 52L;
        }

        String yearString = Long.toString(1960L + years);
        String dayInYearString = new DecimalFormat("000").format((left * 7) + 1);
        String yearDayInYearString = yearString + "-" + dayInYearString;

        Date tempDate = null;
        try {
            tempDate = new SimpleDateFormat("yyyy-DDD").parse(yearDayInYearString);
        } catch (ParseException ex) {
            throw new IOException(ex);
        }

        decodedDateTime = sdf_ymd.format(tempDate.getTime());
        format = sdf_ymd.toPattern();

    } else if (FormatType.matches("^%t?m.*")) {
        // month 
        long monthYears = Long.parseLong(rawDatum);
        long left = Math.abs(monthYears) % 12L;
        long years;
        if (monthYears < 0L) {
            left = 12L - left;
            //out.println("left="+left);
            years = (Math.abs(monthYears) - 1) / 12L + 1L;
            years *= -1L;
        } else {
            years = monthYears / 12L;
        }

        String month = null;
        if (left == 12L) {
            left = 0L;
        }
        Long monthdata = (left + 1);
        month = "-" + twoDigitFormatter.format(monthdata) + "-01";
        long year = 1960L + years;
        String monthYear = Long.toString(year) + month;
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("rawDatum=" + rawDatum + ": monthYear=" + monthYear);

        decodedDateTime = monthYear;
        format = "yyyy-MM-dd";
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("tm:" + decodedDateTime + ", format:" + format);

    } else if (FormatType.matches("^%t?q.*")) {
        // quater
        long quaterYears = Long.parseLong(rawDatum);
        long left = Math.abs(quaterYears) % 4L;
        long years;
        if (quaterYears < 0L) {
            left = 4L - left;
            //out.println("left="+left);
            years = (Math.abs(quaterYears) - 1) / 4L + 1L;
            years *= -1L;
        } else {
            years = quaterYears / 4L;
        }

        String quater = null;

        if ((left == 0L) || (left == 4L)) {
            //quater ="q1"; //
            quater = "-01-01";
        } else if (left == 1L) {
            //quater = "q2"; //
            quater = "-04-01";
        } else if (left == 2L) {
            //quater = "q3"; //
            quater = "-07-01";
        } else if (left == 3L) {
            //quater = "q4"; //
            quater = "-11-01";
        }

        long year = 1960L + years;
        String quaterYear = Long.toString(year) + quater;
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("rawDatum=" + rawDatum + ": quaterYear=" + quaterYear);

        decodedDateTime = quaterYear;
        format = "yyyy-MM-dd";
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("tq:" + decodedDateTime + ", format:" + format);

    } else if (FormatType.matches("^%t?h.*")) {
        // half year
        // odd number:2nd half
        // even number: 1st half

        long halvesYears = Long.parseLong(rawDatum);
        long left = Math.abs(halvesYears) % 2L;
        long years;
        if (halvesYears < 0L) {
            years = (Math.abs(halvesYears) - 1) / 2L + 1L;
            years *= -1L;
        } else {
            years = halvesYears / 2L;
        }

        String half = null;
        if (left != 0L) {
            // odd number => 2nd half: "h2"
            //half ="h2"; //
            half = "-07-01";
        } else {
            // even number => 1st half: "h1"
            //half = "h1"; //
            half = "-01-01";
        }
        long year = 1960L + years;
        String halfYear = Long.toString(year) + half;
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("rawDatum=" + rawDatum + ": halfYear=" + halfYear);

        decodedDateTime = halfYear;
        format = "yyyy-MM-dd";
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("th:" + decodedDateTime + ", format:" + format);

    } else if (FormatType.matches("^%t?y.*")) {
        // year type's origin is 0 AD
        decodedDateTime = rawDatum;
        format = "yyyy";
        if (dbgLog.isLoggable(Level.FINER))
            dbgLog.finer("th:" + decodedDateTime);
    } else {
        decodedDateTime = rawDatum;
        format = null;
    }
    DecodedDateTime retValue = new DecodedDateTime();
    retValue.decodedDateTime = decodedDateTime;
    retValue.format = format;
    return retValue;
}

From source file:foodsimulationmodel.pathmapping.Route.java

/**
 * Used to create a new BuildingsOnRoadCache object. This function is used instead of the constructor directly so
 * that the class can check if there is a serialised version on disk already. If not then a new one is created and
 * returned.//from w w w .  j a  va 2  s  .  c om
 * 
 * @param buildingEnv
 * @param buildingsFile
 * @param roadEnv
 * @param roadsFile
 * @param serialisedLoc
 * @param geomFac
 * @return
 * @throws Exception
 */
public synchronized static NearestRoadCoordCache getInstance(Geography<IAgent> buildingEnv, File buildingsFile,
        Geography<Road> roadEnv, File roadsFile, File serialisedLoc, GeometryFactory geomFac) throws Exception {
    double time = System.nanoTime();
    // See if there is a cache object on disk.
    if (serialisedLoc.exists()) {
        FileInputStream fis = null;
        ObjectInputStream in = null;
        NearestRoadCoordCache ncc = null;
        try {

            fis = new FileInputStream(serialisedLoc);
            in = new ObjectInputStream(fis);
            ncc = (NearestRoadCoordCache) in.readObject();
            in.close();

            // Check that the cache is representing the correct data and the
            // modification dates are ok
            if (!buildingsFile.getAbsolutePath().equals(ncc.buildingsFile.getAbsolutePath())
                    || !roadsFile.getAbsolutePath().equals(ncc.roadsFile.getAbsolutePath())
                    || buildingsFile.lastModified() > ncc.createdTime
                    || roadsFile.lastModified() > ncc.createdTime) {
                LOGGER.log(Level.FINE, "BuildingsOnRoadCache, found serialised object but it doesn't match the "
                        + "data (or could have different modification dates), will create a new cache.");
            } else {
                LOGGER.log(Level.FINER, "NearestRoadCoordCache, found serialised cache, returning it (in "
                        + 0.000001 * (System.nanoTime() - time) + "ms)");
                return ncc;
            }
        } catch (IOException ex) {
            if (serialisedLoc.exists())
                serialisedLoc.delete(); // delete to stop problems loading incomplete file next tinme
            throw ex;
        } catch (ClassNotFoundException ex) {
            if (serialisedLoc.exists())
                serialisedLoc.delete();
            throw ex;
        }

    }

    // No serialised object, or got an error when opening it, just create a new one
    return new NearestRoadCoordCache(buildingEnv, buildingsFile, roadEnv, roadsFile, serialisedLoc, geomFac);
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private synchronized LogIndex unpauseLogIndex(String paxosID) {
    if (isClosed() /* || !isLoggingEnabled() */)
        return null;

    log.log(Level.FINER, "{0} trying to unpause logIndex for {1}", new Object[] { this, paxosID });
    PreparedStatement pstmt = null;
    ResultSet rset = null;//from w ww  .j a  v  a2  s . c om
    Connection conn = null;
    LogIndex logIndex = null;
    String logIndexString = null;
    try {
        conn = this.getDefaultConn();
        pstmt = this.getPreparedStatement(conn, (USE_CHECKPOINTS_AS_PAUSE_TABLE ? getCTable() : getPTable()),
                paxosID, "logindex");
        rset = pstmt.executeQuery();
        while (rset.next()) {
            Blob logIndexBlob = rset.getBlob(1);
            if (logIndexBlob == null)
                continue;
            logIndexString = (lobToString(logIndexBlob));
            logIndex = new LogIndex(new JSONArray(logIndexString));
            this.messageLog.restore(logIndex);
            log.log(Level.FINE, "{0} unpaused logIndex for {1}", new Object[] { this, paxosID });
        }
    } catch (SQLException | JSONException | IOException e) {
        log.severe(this + " failed to unpause instance " + paxosID + "; logIndex = " + logIndexString);
        e.printStackTrace();
    } finally {
        cleanup(pstmt, rset);
        cleanup(conn);
    }
    return logIndex;
}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * Handles the <code>request=login2</code> request. <br>
 * <br>//from  w ww. j a  va 2  s  .  c o m
 * <b>Description:</b> <br>
 * The request created by the HTML page presented by the <code>handleLogin1</code> function, is verified here.<br>
 * For the entered user-id a lookup is done in the user database to determine all enabled AuthSP's for this user.
 * For every AuthSP a verification is done if it matches the required level.<br>
 * All valid AuthSP's are presented to the user by means of a 'drop-down' list in a HTML page. This HTML page will
 * POST a <code>request=login3</code>.<br>
 * Depending on the A-Select configuration <code>always_show_select_form</code> the request can be parsed to
 * <code>handleLogin3()</code> immediately if only one valid AuthSP is found. <br>
 * <br>
 * <b>Concurrency issues:</b> <br>
 * - <br>
 * <br>
 * <b>Preconditions:</b> <br>
 * - <br>
 * <br>
 * <b>Postconditions:</b> <br>
 * - <br>
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            Used to write information back to the user (HTML)
 *            
 * @return 0 = success, 1=bad user input (back to login1)
 * 
 * @throws ASelectException
 */
private int handleLogin2(HashMap htServiceRequest, HttpServletResponse servletResponse, PrintWriter pwOut)
        throws ASelectException {
    String sRid = null;
    String sUid = null;
    String sMethod = "handleLogin2";

    StringBuffer sb;
    _systemLogger.log(Level.INFO, _sModule, sMethod, "Login2 " + htServiceRequest);

    ASelectConfigManager configManager = ASelectConfigManager.getHandle();
    String sUserInfo = configManager.getUserInfoSettings();
    boolean bAuthspFromSelect = sUserInfo.contains("authsps_from_select");
    try {
        sRid = (String) htServiceRequest.get("rid");
        String sAuthsp = (String) _htSessionContext.get("forced_authsp");
        String sAppId = (String) _htSessionContext.get("app_id"); // RH, 20140424, n
        if (sAuthsp != null) {
            // Bauke 20080511: added
            // Redirect to the AuthSP's ISTS
            String sAsUrl = _configManager.getRedirectURL(); // <redirect_url> in aselect.xml
            sAsUrl = sAsUrl + "/" + sAuthsp + "?rid=" + sRid; // e.g. saml20_ists
            // RH, 20100907, sn, add app_id, requestorfriendlyname so authsp can use this at will
            //            String sAppId = (String) _htSessionContext.get("app_id");  // 20101027 // RH, 20140424, o, moved to top
            String sFName = null;
            try {
                sFName = _applicationManager.getFriendlyName(sAppId);
                if (sFName != null && !"".equals(sFName)) {
                    sAsUrl = sAsUrl + "&" + "requestorfriendlyname" + "=" + URLEncoder.encode(sFName, "UTF-8");
                }
            } catch (ASelectException ae) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod,
                        "Redirect without FriendlyName. Could not find or encode FriendlyName for: " + sAppId);
            }
            // RH, 20100907, en

            _systemLogger.log(Level.INFO, _sModule, sMethod,
                    "REDIR to " + sAsUrl + " forced_authsp=" + sAuthsp);
            servletResponse.sendRedirect(sAsUrl);
            return 0;
        }
        // Has done it's work if present, note that getAuthsps() will store the session
        _htSessionContext.remove("forced_uid"); // 20101027 _, solves JDBC issue where forced_uid was not removed!
        _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: added

        sUid = (String) htServiceRequest.get("user_id");
        if (sUid == null) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "Invalid request, missing parmeter 'user_id'");
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        // If uid contains spaces, they where transformed to '+'
        // Translate them back.
        try {
            sUid = URLDecoder.decode(sUid, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "Failed to decode user id.");
            throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
        }

        // RH, 20140424, sn
        Integer iSubLevel = null;
        try {
            iSubLevel = _applicationManager.getSubLevel(sAppId);
            _htSessionContext.put("sub_level", iSubLevel); // need not be saved
        } catch (ASelectException ae) {
            _systemLogger.log(Level.FINER, _sModule, sMethod, "No min_level found for application: " + sAppId);
        }
        _sessionManager.setUpdateSession(_htSessionContext, _systemLogger);
        // RH, 20140424, en

        try {
            // Get authsps for this user, result is a collection of authsps with a login name to be used for that authsp
            // Stored in the session under "allowed_user_authsps"
            getUserAuthsps(sRid, sUid); // will update _htSessionContext!
        } catch (ASelectException e) {
            if (_crossASelectManager.isCrossSelectorEnabled() && _configManager.isCrossFallBackEnabled()) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod,
                        "Failed to retrieve AuthSPs for user=" + sUid + " goto CROSS");
                handleCrossLogin(htServiceRequest, servletResponse, pwOut);
                return 0;
            }
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "Failed to retrieve AuthSPs for user " + sUid);
            // Would like to go back to login1 to give the user another chance
            _htSessionContext.put("error_message", Errors.ERROR_ASELECT_SERVER_USER_NOT_ALLOWED);
            _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: added
            return 1;
        }

        // Bauke: added shortcut when using "Verkeersplein" method
        String sFixedAuthsp = (String) _htSessionContext.get("fixed_authsp");
        if (sFixedAuthsp != null) {
            _systemLogger.log(Level.INFO, _sModule, sMethod, "fixed_authsp=" + sFixedAuthsp);
            htServiceRequest.put("authsp", sFixedAuthsp);

            // Also save entered uid as 'sel_uid'
            String sUserId = (String) _htSessionContext.get("user_id");
            if (sUserId != null) {
                htServiceRequest.put("sel_uid", sUserId);
                _htSessionContext.put("sel_uid", sUserId);
                _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: added
            }
            String sFixedUid = (String) _htSessionContext.get("fixed_uid");
            if (sFixedUid != null) {
                // From here on use the fixed_uid as 'user_id'
                _systemLogger.log(Level.INFO, _sModule, sMethod, "Fixed user_id=" + sFixedUid);
                htServiceRequest.put("user_id", sFixedUid);
                _htSessionContext.put("user_id", sFixedUid);
                _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: added
            }
            handleLogin3(htServiceRequest, servletResponse, pwOut);
            return 0;
        }

        // We now have the list of authsps that the user may use. Show the selectform
        HashMap htAuthsps = (HashMap) _htSessionContext.get("allowed_user_authsps");
        // Should the user be bothered with the selection form
        // if only one method is available?
        String sFormShow = _configManager.getParam(_configManager.getSection(null, "authsps"),
                "always_show_select_form");
        _systemLogger.log(Level.INFO, _sModule, sMethod,
                "User=" + sUid + " Authsps=" + htAuthsps + " always_show_select_form=" + sFormShow);
        if (htAuthsps.size() == 1 && !bAuthspFromSelect) {
            try {
                if (sFormShow.equalsIgnoreCase("false")) {
                    // continue with login3
                    Set keys = htAuthsps.keySet();
                    for (Object s : keys) {
                        htServiceRequest.put("authsp", (String) s);
                        break;
                    }
                    _systemLogger.log(Level.INFO, _sModule, sMethod, "Single authsp, goto login3");
                    handleLogin3(htServiceRequest, servletResponse, pwOut);
                    return 0;
                }
            } catch (ASelectConfigException e) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod,
                        "Failed to retrieve config 'always_show_select_form'. Using default (yes).");
            }
        }
        // end only 1 valid authsp or bAuthspFromSelect

        // Multiple candidates, present the select.html form
        _systemLogger.log(Level.INFO, _sModule, sMethod,
                "Multiple authsps or 'authsps_from_select' was set: show 'select' form");
        // 20130514, Bauke: remember what the user sees on the screen
        _htSessionContext.put("user_state", "state_select");
        _sessionManager.setUpdateSession(_htSessionContext, _systemLogger);

        // RH, 20121119, sn
        // Handle application specific select form
        String sSelectFormName = SELECTFORMPREFIX;
        //         String sAppId = (String) _htSessionContext.get("app_id");   // RH, 20121119, o, moved to top
        if (sAppId != null && (_applicationManager.getSelectForm(sAppId) != null)) {
            sSelectFormName += _applicationManager.getSelectForm(sAppId); // Add application specific suffix
            _systemLogger.log(Level.INFO, _sModule, sMethod,
                    "Found application specific select form: " + sSelectFormName + " for app_id: " + sAppId);
        }
        String sSelectForm = _configManager.getHTMLForm(sSelectFormName, _sUserLanguage, _sUserCountry);

        sSelectForm = Utils.replaceString(sSelectForm, "[rid]", sRid);
        sSelectForm = Utils.replaceString(sSelectForm, "[a-select-server]", _sMyServerId);
        sSelectForm = Utils.replaceString(sSelectForm, "[user_id]", sUid);
        sSelectForm = Utils.replaceString(sSelectForm, "[aselect_url]",
                (String) htServiceRequest.get("my_url"));
        sSelectForm = Utils.replaceString(sSelectForm, "[request]", "login3");
        String sLanguage = (String) _htSessionContext.get("language"); // 20101027 _
        String sCountry = (String) _htSessionContext.get("country"); // 20101027 _
        sSelectForm = Utils.replaceString(sSelectForm, "[language]", sLanguage);
        sSelectForm = Utils.replaceString(sSelectForm, "[country]", sCountry);

        // 20130411: What AuthSP's must be presented to the user?
        if (bAuthspFromSelect) {
            // 20130411, Bauke: Take AuthSP's from select.html
            String sUrl = "", sName = "", sSelectChoice = "";

            try {
                sSelectChoice = HandlerTools.getEncryptedCookie(_servletRequest, select_choice_COOKIE,
                        _systemLogger);
            } catch (ASelectException ae) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod,
                        "Could not decrypt cookie: " + select_choice_COOKIE);
            }
            if (Utils.hasValue(sSelectChoice)) {
                _systemLogger.log(Level.INFO, _sModule, sMethod, "select_choice=" + sSelectChoice);
                // Earlier choice present, get it selected
                // Contents of the cookie: <authsp_url>;<authsp_name>
                // In the form look for: <option value="..." ...
                // Note the authsp_name can contain double quotes, they must be escaped for HTML usage.
                sSelectChoice = sSelectChoice.replaceAll("\"", "&quot;");
                int idxChoice = sSelectForm.indexOf(sSelectChoice);
                if (idxChoice >= 0) {
                    // Cookie choice is still present in the form, "select" it
                    int idxValue = sSelectForm.lastIndexOf("value", idxChoice);
                    if (idxValue >= 0) {
                        sSelectForm = sSelectForm.substring(0, idxValue).concat("selected ")
                                .concat(sSelectForm.substring(idxValue));
                    }
                    // Replacements in the form, split using the semicolon
                    // If no semicolon is present, we only have the "url" part available.
                    sUrl = sSelectChoice;
                    int idx = sSelectChoice.indexOf(';');
                    if (idx >= 0) {
                        sUrl = sSelectChoice.substring(0, idx);
                        sName = sSelectChoice.substring(idx + 1);
                    }
                }
            }

            sSelectForm = Utils.replaceString(sSelectForm, "[authsp_url]", sUrl);
            sSelectForm = Utils.replaceString(sSelectForm, "[authsp_name]", sName);
            _systemLogger.log(Level.INFO, _sModule, sMethod, "url=" + sUrl + " name=" + sName);
        } else { // The Classic Solution, take authsp's from the configuration
            String sFriendlyName = "";
            String sAuthspName = "";
            sb = new StringBuffer();
            Set<String> keys = htAuthsps.keySet();

            for (Object s : keys) {
                sAuthspName = (String) s;
                try {
                    Object authSPsection = _configManager.getSection(_configManager.getSection(null, "authsps"),
                            "authsp", "id=" + sAuthspName);
                    sFriendlyName = _configManager.getParam(authSPsection, "friendly_name");
                    sb.append("<OPTION VALUE=").append(sAuthspName).append(">");
                    sb.append(sFriendlyName);
                    sb.append("</OPTION>");
                } catch (ASelectConfigException ace) {
                    _systemLogger.log(Level.WARNING, _sModule, sMethod,
                            "Failed to retrieve config for AuthSPs.");
                    throw ace;
                }
            }
            sSelectForm = Utils.replaceString(sSelectForm, "[allowed_user_authsps]", sb.toString());
        }

        // Create the Cancel action:
        sb = new StringBuffer((String) htServiceRequest.get("my_url")).append("?request=error")
                .append("&result_code=").append(Errors.ERROR_ASELECT_SERVER_CANCEL).append("&a-select-server=")
                .append(_sMyServerId).append("&rid=").append(sRid);

        sSelectForm = Utils.replaceString(sSelectForm, "[cancel]", sb.toString());
        sSelectForm = _configManager.updateTemplate(sSelectForm, _htSessionContext, _servletRequest);
        // _systemLogger.log(Level.FINER, _sModule, sMethod, "Form select=["+sSelectForm+"]");
        Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext); //20111102
        //_sessionManager.update(sRid, _htSessionContext); // Write session
        // pauseSensorData does this already: _sessionManager.setUpdateSession(_htSessionContext, _systemLogger);  // 20120401, Bauke: changed, was update()
        pwOut.println(sSelectForm);
        return 0;
    } catch (ASelectException ae) {
        throw ae;
    } catch (Exception e) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Internal error", e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    }
}

From source file:edu.umass.cs.gigapaxos.PaxosManager.java

private void syncAndDeactivate() {
    if (isClosed() || this.pinstances.size() == 0)
        return;//from   ww  w  .  j a va 2 s.  c  o  m
    if (!this.shouldTryDeactivation())
        return;

    long t0 = System.currentTimeMillis();
    RateLimiter rateLimiter = new RateLimiter(PAUSE_RATE_LIMIT);
    log.log(Level.FINE, "{0} initiating deactivation attempt, |activePaxii| = {1}",
            new Object[] { this, this.pinstances.size() });
    int numPaused = 0;
    Map<String, PaxosInstanceStateMachine> batch = new HashMap<String, PaxosInstanceStateMachine>();

    // cuckoo hashmap now supports an efficient iterator
    for (Iterator<PaxosInstanceStateMachine> pismIter = this.pinstances.concurrentIterator(); pismIter
            .hasNext();) {
        PaxosInstanceStateMachine pism = pismIter.next();

        String paxosID = pism.getPaxosID();

        if (pism.isLongIdle()
                // if size > capacity/2, pause 1/FORCE_PAUSE_FACTOR fraction
                || (this.pinstances.size() > this.pinstances.capacity() / 2
                        && numPaused < this.pinstances.capacity() / FORCE_PAUSE_FACTOR)) {
            log.log(Level.FINER, "{0} trying to pause {1} [{2}]", new Object[] { this, paxosID, pism });
            /* The sync below ensures that, at least once every deactivation
             * period, we sync decisions for an active paxos instance. This
             * is handy when a paxos instance is not caught up but doesn't
             * get any new messages either, say, because nothing new is
             * happening, then it has no reason to do anything but will
             * remain unnecessarily active; the sync here allows it to
             * potentially catch up and possibly be paused in the next
             * deactivation round if there is still no action by then. The
             * sync is useful irrespective of whether or not the instance is
             * caught up for pausability
             * 
             * Overhead: This sync imposes a message overhead of up to A
             * messages A is the number of active paxos instances. For
             * example, with 10K active instances, this method could send
             * 10K messages, which is high. However, for each instance, the
             * sync message will get sent only if it has not recently sent a
             * sync message *and* it is out of sync or it has just started
             * up and has a very low outOfOrder limit. Consequently, we
             * should avoid having a large number of paxos instances with a
             * very low outOfOrderLimit, especially if all they plan to do
             * is to start up and do nothing, otherwise, they will cause a
             * one-time deluge of sync messages before being paused.
             * 
             * If active instances are generally busy but out of sync, we
             * could impose a bandwidth overhead of A/D where D is the
             * deactivation thread's period, e.g., A=10K, D=30secs => an
             * overhead of 333 messages/sec, which although seems high is
             * possible only if none of those paxos instances sent a sync
             * reauest in the last S seconds, where S is the minimum
             * inter-sync interval for each instance (default 1 second). In
             * expectation, a high overhead relative to the inevitable paxos
             * commit overhead (of 3 messages per replica per decision) is
             * unlikely unless the workload and network behave
             * adversarially, i.e., in every D period, each active paxos
             * instance executes just enough decisions for it to be possible
             * for its outOfOrder threshold to be triggered and the network
             * reorders some of those decisions. If the instance commits
             * many more decisions than the outOfOrder threshold, then the
             * sync message adds only a small relative overhead, e.g., if
             * the outOfOrder threshold is 10, roughly 33 messages (accept,
             * acceptReply, decision) would be required to commit at least
             * 11 decisions that would then trigger just one sync message.
             * If the outOfOrder threshold is 1, then the sync message could
             * add one message to every 6 expected messages (for 2 paxos
             * commits) at this replica, a ~15% overhead. But with such a
             * low outOfOrder threshold, we should not be having a large
             * number of paxos instances in the first place. */
            this.syncPaxosInstance(pism, false);
            // rate limit if well under capacity
            if (this.pinstances.size() < this.pinstances.capacity() / FORCE_PAUSE_FACTOR)
                rateLimiter.record();
            batch.put(pism.getPaxosID(), pism);
            if (batch.size() >= PAUSE_BATCH_SIZE) {
                Set<String> batchPaused = pause(batch, true);
                if (batchPaused != null)
                    numPaused += batchPaused.size();
                log.log(Level.FINE, "{0} paused {1}", new Object[] { this, batchPaused });
                this.printPauseLog(batchPaused);
                batch.clear();
            }
        }
    }
    if (!batch.isEmpty()) {
        this.printPauseLog(this.pause(batch, true));
    }
    DelayProfiler.updateDelay("deactivation", t0);
}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * This methods handles the <code>request=login3</code> request. <br>
 * <br>/*w  w w  . j a v  a2s  .co m*/
 * <b>Description:</b> <br>
 * The user has now chosen a method for authentication and is ready to be redirected to the AuthSP's authentication
 * page. <br>
 * The protocol handler for the AuthSP is instantiated and that object will compute the request for authentication
 * (e.g., it will also sign the request). The actual method that does this is <code>startAuthentication</code>.<br>
 * If everything is ok, the user is redirected through the <code>servletResponse.sendRedirect()</code> method with a
 * signed request for the AuthSP. <br>
 * <br>
 * <br>
 * <b>Concurrency issues:</b> <br>
 * - <br>
 * <br>
 * <b>Preconditions:</b> <br>
 * - <br>
 * <br>
 * <b>Postconditions:</b> <br>
 * - <br>
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            Used to write information back to the user (HTML)
 * @throws ASelectException
 *             the a select exception
 */
private void handleLogin3(HashMap htServiceRequest, HttpServletResponse servletResponse, PrintWriter pwOut)
        throws ASelectException {
    String sRid = null;
    String sAuthsp = null;
    String sMethod = "handleLogin3";
    String sRedirectUrl = null;
    String sPopup = null;

    _systemLogger.log(Level.INFO, _sModule, sMethod, "login3 " + htServiceRequest);
    try {
        sRid = (String) htServiceRequest.get("rid");
        sAuthsp = (String) htServiceRequest.get("authsp");
        if (sAuthsp == null) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "Invalid request, missing parmeter 'authsp'");
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }
        // 20130411, Bauke: moved before the "authsp_from_select" code
        String sAppId = (String) _htSessionContext.get("app_id");
        String sFriendlyName = null;
        try {
            sFriendlyName = _applicationManager.getFriendlyName(sAppId);
        } catch (ASelectException ae) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod,
                    "Redirect without FriendlyName. Could not find or encode FriendlyName for: " + sAppId);
        }
        // RH, 20100907, en

        // 20130411, Bauke: Register the choice made by the user
        ASelectConfigManager configManager = ASelectConfigManager.getHandle();
        String sUserInfo = configManager.getUserInfoSettings();

        // 20120815, Bauke: Before startAuthentication, because it reads from config
        Object authSPsection = getAuthspParametersFromConfig(sAuthsp);

        String sSaveAppId = sAppId; // save session version of app_id
        boolean bAuthspFromSelect = sUserInfo.contains("authsps_from_select");
        String sChosenAppId = (String) htServiceRequest.get("app_id"); // looks like <url_or_id>;<user_frienly_name>
        String sSocialLogin = (String) htServiceRequest.get("social_login"); // 20140216, Bauke: added
        _systemLogger.log(Level.INFO, _sModule, sMethod, "app_id=" + sAppId + " chosenAppId=" + sChosenAppId
                + " authsps_from_select=" + bAuthspFromSelect + " social_login=" + sSocialLogin);
        if (bAuthspFromSelect && Utils.hasValue(sChosenAppId)) {
            // Save user choice (value of app_id) in the cookie
            // Note: use the server's cookie domain, not the one set in the AuthSP, see getAuthspParametersFromConfig()
            // 20130502, Bauke: Handled by the test above:
            //if (!Utils.hasValue(sChosenAppId)) {
            //   _systemLogger.log(Level.WARNING, _sModule, sMethod, "No app_id found in request, \"authsps_from_select\"=true");
            //   throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
            //}

            // Split sChosenAppId
            // Note the authsp_name can contain double quotes, they must be escaped for HTML usage.
            // but the name is not used here: sChosenAppId = sChosenAppId.replaceAll("\"", "&quot;");
            // If no semicolon is present, we only have the "url" part available.
            String sChosenPart1 = sChosenAppId;
            int idx = sChosenAppId.indexOf(';');
            if (idx >= 0) {
                sChosenPart1 = sChosenAppId.substring(0, idx);
            }
            _systemLogger.log(Level.INFO, _sModule, sMethod,
                    "Using authsps_from_select mechanism, sChosenAppId=" + sChosenAppId);

            // 20130821, Bauke: introduced setEntrypedCookie() method
            HandlerTools.setEncryptedCookie(servletResponse, select_choice_COOKIE, sChosenAppId,
                    _configManager.getCookieDomain(), 157680101/*5 years*/, _systemLogger);
            // Old:
            //sChosenAppId = _cryptoEngine.encryptData(sChosenAppId.getBytes());  // _configManager.getDefaultPrivateKey());
            //String sCookieDomain = _configManager.getCookieDomain();
            //HandlerTools.putCookieValue(servletResponse, select_choice_COOKIE, sChosenAppId,
            //      sCookieDomain, null, 157680101/*5 years*/, 1/*httpOnly*/, _systemLogger);

            // And temporarily replace the provided "app_id" with the user's choice
            // This value will be used by startAuthentication() to create the redirect_url
            _htSessionContext.put("app_id", sChosenPart1); // need not be saved
        }
        // End of registration

        //   RH, 20140424, sn
        Object oAuthSPsection = _configManager.getSection(_configManager.getSection(null, "authsps"), "authsp",
                "id=" + sAuthsp);
        //         boolean bUDBLookup = _configManager.getParam(oAuthSPsection, "udb_lookup");
        boolean bUDBLookup = false;
        String sUDBLookup = null;
        try {
            sUDBLookup = _configManager.getParam(oAuthSPsection, "udb_lookup");
            bUDBLookup = Boolean.parseBoolean(sUDBLookup);
            _systemLogger.log(Level.FINEST, _sModule, sMethod, "Found udb_lookup=" + sUDBLookup);
        } catch (ASelectConfigException ace) {
            // No problem, just skip
            _systemLogger.log(Level.FINEST, _sModule, sMethod, "Found udb_lookup=" + sUDBLookup);
        }
        if (bUDBLookup) { // do extra udb lookup
            // we want to change user_id but not sure if this will work because tgt might get destroyed when finding other user_id
            // for test get user_id from form
            HashMap htAllowedAuthsps = (HashMap) _htSessionContext.get("allowed_user_authsps");
            _systemLogger.log(Level.FINEST, _sModule, sMethod,
                    "Before lookup htAllowedAuthsps=" + htAllowedAuthsps);
            _systemLogger.log(Level.FINEST, _sModule, sMethod,
                    "Before lookup _htSessionContext=" + _htSessionContext);
            String sUid = (String) _htSessionContext.get("user_id");
            _systemLogger.log(Level.FINEST, _sModule, sMethod, "Looking up in UDB user_id:" + sUid);
            // RH, 20140424, sn
            Integer iSubLevel = null;
            try {
                iSubLevel = _applicationManager.getSubLevel(sAppId);
                _htSessionContext.put("sub_level", iSubLevel); // need not be saved
            } catch (ASelectException ae) {
                _systemLogger.log(Level.FINER, _sModule, sMethod,
                        "No min_level found for application: " + sAppId);
            }
            // RH, 20140424, en

            getUserAuthsps(sRid, sUid);
            htAllowedAuthsps = (HashMap) _htSessionContext.get("allowed_user_authsps");
            _systemLogger.log(Level.FINEST, _sModule, sMethod,
                    "After lookup htAllowedAuthsps=" + htAllowedAuthsps);
        }
        //   RH, 20140424, en

        // 20111013, Bauke: added absent phonenumber handling
        HashMap htResponse = startAuthentication(sRid, htServiceRequest);

        if (bAuthspFromSelect && Utils.hasValue(sChosenAppId)) // restore app_id after startAuthentication() has done it's work
            _htSessionContext.put("app_id", sSaveAppId);

        String sResultCode = (String) htResponse.get("result");
        if (!sResultCode.equals(Errors.ERROR_ASELECT_SUCCESS)) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod,
                    "Failed to create redirect url, result=" + sResultCode);
            throw new ASelectException(sResultCode);
        }

        sRedirectUrl = (String) htResponse.get("redirect_url");
        try {
            try {
                sPopup = _configManager.getParam(authSPsection, "popup");
            } catch (ASelectConfigException e) {
                // No popup configured -> sPopup is null already
            }
            // RH, 20100907, sn, add app_id, requestorfriendlyname so authsp can use this at will
            if (Utils.hasValue(sFriendlyName)) {
                sRedirectUrl = sRedirectUrl + "&" + "requestorfriendlyname" + "="
                        + URLEncoder.encode(sFriendlyName, "UTF-8");
            }
            // RH, 20100907, en
            // 20140216, Bauke: added social login
            //if (Utils.hasValue(sSocialLogin)) {
            //   sRedirectUrl = sRedirectUrl + "&" + "social_login" + "="  +  URLEncoder.encode(sSocialAuth, "UTF-8");
            //}

            _systemLogger.log(Level.INFO, _sModule, sMethod, "REDIRECT " + sRedirectUrl);
            if (sPopup == null || sPopup.equalsIgnoreCase("false")) {
                Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext); //20111102, control goes to a different server
                _htSessionContext.put("authsp_visited", "true");
                _htSessionContext.put("user_state", "state_redirect");
                _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: changed, was update()
                servletResponse.sendRedirect(sRedirectUrl);
                return;
            }

            // must use popup so show the popup page
            String sPopupForm = _configManager.getHTMLForm("popup", _sUserLanguage, _sUserCountry);
            sPopupForm = Utils.replaceString(sPopupForm, "[authsp_url]", sRedirectUrl);
            String strFriendlyName = _configManager.getParam(authSPsection, "friendly_name");
            sPopupForm = Utils.replaceString(sPopupForm, "[authsp]", strFriendlyName);
            sPopupForm = _configManager.updateTemplate(sPopupForm, _htSessionContext, _servletRequest);
            Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext); // 20111102, control to the user

            _htSessionContext.put("user_state", "state_popup");
            _htSessionContext.put("authsp_visited", "true");
            _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: changed, was update()
            pwOut.println(sPopupForm);
            return;
        } catch (ASelectConfigException e) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "Failed to retrieve config for AuthSPs.");
            throw new ASelectException(e.getMessage());
        } catch (IOException e) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "Failed to redirect user.");
            throw new ASelectException(Errors.ERROR_ASELECT_IO);
        }
    } catch (ASelectException ae) {
        throw ae;
    } catch (Exception e) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Internal error", e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    }
}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * This method handles the <code>request=logout</code> user request. <br>
 * <br>/*from   w  ww.j av a2  s .  com*/
 * <b>Description:</b> <br>
 * The request can be used to logout a user by sending a saml logoutrequest. <br>
 * e.g. if the user sends a normal request=logout but actually was a saml user and should have send a samlrequest <br>
 * <br>
 * <b>Preconditions:</b> <br>
 * Valid TGT <br>
 * <br>
 * <b>Postconditions:</b> <br>
 * <br>
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            Used to write information back to the user (HTML)
 * @throws ASelectException
 */
private void handleSamlLogout(HashMap htServiceRequest, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse, PrintWriter pwOut) throws ASelectException {
    String sMethod = "handleSamlLogout";
    String sRemoteAsUrl = null;

    _systemLogger.log(Level.FINER, _sModule, sMethod, "handleSamlLogout");

    String sTgt = (String) htServiceRequest.get("aselect_credentials_tgt");

    if (_htTGTContext != null) { // must be true for samllogout
        LogoutRequestSender logoutRequestSender = new LogoutRequestSender();
        //            String sIssuer = (String)_htTGTContext.get("sp_issuer");
        String sIssuer = _sServerUrl; // set idp as issuer
        String sNameID = (String) _htTGTContext.get("name_id");
        String sAppId = (String) _htTGTContext.get("app_id");
        //  find a way to get the default, maybe from application section
        // If we allow this we must sanitize this url !!!
        String sLogoutReturnUrl = (String) htServiceRequest.get("logout_return_url");
        if (sLogoutReturnUrl != null) {
            _systemLogger.log(Level.FINER, _sModule, sMethod,
                    "Found logout_return_url in request: " + sLogoutReturnUrl);
            // For backward compatibility, avoid double decoding
            boolean doDecode = true; // backward compatibility
            HashMap<String, Vector<String>> parameters2decode = _configManager.getParameters2decode();
            if (parameters2decode != null && !parameters2decode.isEmpty()) {
                Vector<String> appl = parameters2decode.get("logout_return_url");
                if (Utils.hasValue(sAppId) && appl != null && appl.contains(sAppId)) { // already decoded
                    doDecode = false;
                    _systemLogger.log(Level.FINER, _sModule, sMethod, "logout_return_url already urldecoded");
                }
            }
            if (doDecode) {
                try {
                    sLogoutReturnUrl = URLDecoder.decode(sLogoutReturnUrl, "UTF-8");
                    _systemLogger.log(Level.FINER, _sModule, sMethod,
                            "logout_return_url after decoding: " + sLogoutReturnUrl);
                } catch (UnsupportedEncodingException e) {
                    _systemLogger.log(Level.WARNING, _sModule, sMethod,
                            "Unable to urldecode, unsupported encoding UTF-8");
                    throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
                }
            }
        }
        // We need to get the logout url from somewhere too
        String url = _sServerUrl + "/saml20_idp_slo_http_request";

        // 20120611, Bauke: added "usi"
        String sUsi = (String) _htTGTContext.get("usi");
        if (Utils.hasValue(sUsi)) // overwrite
            _timerSensor.setTimerSensorId(sUsi);
        if (Utils.hasValue(sAppId))
            _timerSensor.setTimerSensorAppId(sAppId);

        _systemLogger.log(Level.FINER, _sModule, sMethod, "Compose sendLogoutRequest to: " + url);

        logoutRequestSender.sendLogoutRequest(servletRequest, servletResponse, sTgt, url, sIssuer/* issuer */,
                sNameID, "urn:oasis:names:tc:SAML:2.0:logout:user", sLogoutReturnUrl, null, null);

        return;
    } else {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "No tgt found!");
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
    }
}