Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

In this page you can find the example usage for java.lang StringBuffer substring.

Prototype

@Override
public synchronized String substring(int start) 

Source Link

Usage

From source file:uk.ac.cam.ucs.webauth.RavenFilter.java

@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
        throws IOException, ServletException {

    // Only process http requests.
    if ((servletReq instanceof HttpServletRequest) == false) {
        String msg = "Configuration Error.  RavenFilter can only handle Http requests. The rest of the filter chain will NOT be processed.";
        log.error(msg);// w  ww.j av  a 2 s.co  m
        return;
    }

    if (testingMode) {
        servletReq.setAttribute(ATTR_REMOTE_USER, "test");
        ((HttpServletRequest) servletReq).getSession().setAttribute(ATTR_REMOTE_USER, "test");
        chain.doFilter(servletReq, servletResp);
        return;
    }

    HttpServletRequest request = (HttpServletRequest) servletReq;
    HttpServletResponse response = (HttpServletResponse) servletResp;
    HttpSession session = request.getSession();

    log.debug("RavenFilter running for: " + request.getServletPath());

    // Check for an authentication reply in the request
    // If its a POST request then we cannot read parameters because this
    // trashes the inputstream which we want to pass to the servlet. So, if
    // its a post request then assume that there is no WLS-RESPONSE in the
    // request. This is reasonable because WLS-Response is sent from the
    // raven server and it won't do that with a POST request.
    String wlsResponse = null;
    if (!"POST".equals(request.getMethod())) {
        wlsResponse = request.getParameter(WLS_RESPONSE_PARAM);
        log.debug("WLS-Response is " + wlsResponse);
    } else {
        log.debug("Not checking WLS-Response because we have a POST request");
    }

    // WebauthResponse storedResponse = (WebauthResponse)
    // session.getAttribute(WLS_RESPONSE_PARAM);
    WebauthRequest storedRavenReq = (WebauthRequest) session.getAttribute(SESS_RAVEN_REQ_KEY);
    log.debug("Stored raven request is " + storedRavenReq);
    RavenState storedState = (RavenState) session.getAttribute(SESS_STORED_STATE_KEY);
    log.debug("Stored state is " + storedState);
    /*
     * Check the stored state if we have it
     */
    if (storedState != null) {
        if (storedState.status != 200) {
            session.setAttribute(SESS_STORED_STATE_KEY, null);
            response.sendError(storedState.status);
            return;
        }

        /*
         * We do not check for expiry of the state because in this
         * implementation we simply use the session expiry the web admin has
         * configured in Tomcat (since the Raven authentication is only used
         * to set up the session, it makes sense to use the session's expiry
         * rather than Raven's).
         */

        /*
         * We do not check for state.last or state.issue being in the
         * future. State.issue is already checked in the WebauthValidator
         * when the state is initially created. State.last is set by
         * System.currentTimeMillis at state creation time and therefore
         * cannot be in the future.
         */

        if (wlsResponse == null || wlsResponse.length() == 0) {
            log.debug("Accepting stored session");
            if (allowedPrincipals == null || allowedPrincipals.contains(storedState.principal.getName())) {
                chain.doFilter(request, response);
                return;
            } else {
                response.sendError(403, "You are not authorized to view this page.");
                return;
            }
        }
    } // end if (storedState != null)

    /*
     * Check the received response if we have it.
     * 
     * Note - if we have both a stored state and a WLS-Response, we let the
     * WLS-Response override the stored state (this is no worse than if the
     * same request arrived a few minutes later when the first session would
     * have expired, thus removing the stored state)
     */
    if (wlsResponse != null && wlsResponse.length() > 0) {
        WebauthResponse webauthResponse = new WebauthResponse(wlsResponse);
        session.setAttribute(WLS_RESPONSE_PARAM, webauthResponse);
        try {
            log.debug("Validating received response with stored request");
            if (storedRavenReq == null) {
                response.sendError(500, "Failed to find a stored Raven request in the user's session.");
                return;
            }
            this.getWebauthValidator().validate(storedRavenReq, webauthResponse);

            RavenPrincipal principal = new RavenPrincipal(webauthResponse.get("principal"));
            RavenState state = new RavenState(200, webauthResponse.get("issue"), webauthResponse.get("life"),
                    webauthResponse.get("id"), principal, webauthResponse.get("auth"),
                    webauthResponse.get("sso"), webauthResponse.get("params"));

            log.debug("Storing new state " + state.toString());
            session.setAttribute(SESS_STORED_STATE_KEY, state);
            session.setAttribute(ATTR_REMOTE_USER, state.principal.getName());
            request.setAttribute(ATTR_REMOTE_USER, state.principal.getName());

            /*
             * We do a redirect here so the user doesn't see the
             * WLS-Response in his browser location
             */
            response.sendRedirect(webauthResponse.get("url"));
            return;
        } catch (WebauthException e) {
            log.debug("Response validation failed - " + e.getMessage());
            try {
                int status = webauthResponse.getInt("status");
                if (status > 0)
                    response.sendError(status, e.getMessage());
                else
                    response.sendError(500, "Response validation failed - " + e.getMessage());
            } catch (Exception e2) {
                response.sendError(500, "Response validation failed - " + e.getMessage());
            }
            return;
        }
    } else {
        /*
         * No WLS-Response, no stored state. Redirect the user to Raven to
         * log in
         */
        WebauthRequest webauthReq = new WebauthRequest();

        StringBuffer url = request.getRequestURL();
        if (serverURLPrefix != null) {
            // strip off everything up to and including the servlet path and
            // replace with the prefix
            String contextPath = request.getContextPath();
            log.debug("Context path is: " + contextPath);
            log.debug("Request url is: " + request.getRequestURL());
            int index = url.indexOf(contextPath);
            if (index == -1) {
                log.error("Failed to find context path (" + contextPath + ") in request url " + url);
            } else {
                url = new StringBuffer(serverURLPrefix + url.substring(index + contextPath.length()));
            }
        }

        if (request.getQueryString() != null && request.getQueryString().length() > 0) {
            url.append('?');
            url.append(request.getQueryString());
        }
        log.debug("Redirecting with url " + url.toString());
        webauthReq.set("url", url.toString());
        session.setAttribute(SESS_RAVEN_REQ_KEY, webauthReq);
        response.sendRedirect(sRavenAuthenticatePage + "?" + webauthReq.toQString());
        return;
    }
}

From source file:org.apache.ode.bpel.compiler.v1.xpath20.XPath20ExpressionCompilerImpl.java

/**
 * Returns the list of variable references in the given XPath expression
 * that may not have been resolved properly, which is the case especially 
 * if the expression contains a function, which short circuited the evaluation.
 *  /*from   w w  w . j  av a 2s .c o m*/
 * @param xpathStr
 * @return list of variable expressions that may not have been resolved properly
 */
private List<String> extractVariableExprs(String xpathStr) {
    ArrayList<String> variableExprs = new ArrayList<String>();
    int firstVariable = xpathStr.indexOf("$"), lastVariable = xpathStr.lastIndexOf("$"),
            firstFunction = xpathStr.indexOf("(");
    if ((firstVariable > 0 && // the xpath references a variable
            firstFunction > 0) || // the xpath contains a function
            (firstVariable < lastVariable)) { // the xpath references multiple variables  
        // most likely, the variable reference has not been resolved, so make that happen
        StringBuffer variableExpr = new StringBuffer();
        boolean quoted = false, doubleQuoted = false, variable = false;
        Name11Checker nameChecker = Name11Checker.getInstance();
        for (int index = 0; index < xpathStr.length(); index++) {
            char ch = xpathStr.charAt(index);
            if (ch == '\'') {
                quoted = !quoted;
            }
            if (ch == '\"') {
                doubleQuoted = !doubleQuoted;
            }
            if (quoted || doubleQuoted) {
                continue;
            }
            if (ch == '$') {
                variable = true;
                variableExpr.setLength(0);
                variableExpr.append(ch);
            } else {
                if (variable) {
                    variableExpr.append(ch);
                    // in the name is qualified, don't check if its a qname when we're at the ":" character
                    if (ch == ':') {
                        continue;
                    }
                    if (index == xpathStr.length() || !nameChecker.isQName(variableExpr.substring(1))) {
                        variable = false;
                        variableExpr.setLength(variableExpr.length() - 1);
                        variableExprs.add(variableExpr.toString());
                    }
                }
            }
        }
    }
    return variableExprs;
}

From source file:org.etudes.mneme.impl.ImporteCollegeTextServiceImpl.java

public void importQuestions(String context, Pool pool, String text) throws AssessmentPermissionException {
    if ((text == null) || (text.length() == 0))
        return;//  w w w. jav  a 2s  . c om

    // replace any \r\n with just a \n
    text = text.replaceAll("\r\n", "\n");

    String title = "eCollege paste";
    Float points = new Float("1");

    if (pool == null) {
        pool = this.poolService.newPool(context);
        //read title from the first line ex: Unit 2: Week 2 - Quiz
        String findTitle = text.substring(0, text.indexOf("\n"));
        if (findTitle != null) {
            String[] titleParts = findTitle.split("[:-]");
            if (titleParts.length == 2 && titleParts[1] != null && titleParts[1].length() != 0)
                title = titleParts[1].trim();
            else if (titleParts.length > 2)
                title = findTitle.substring(findTitle.indexOf(titleParts[1]));
        }
        pool.setTitle(title);
        pool.setPointsEdit(points);

        // create assessment
        Assessment assmt = assessmentService.newAssessment(context);
        assmt.setType(AssessmentType.test);
        assmt.setTitle(title);

        Part part = assmt.getParts().addPart();

        Pattern p_groups = Pattern.compile("Collapse[\\s]*Question(.*?)[\\n]*[\\t]*row[\\t]*Move[\\s]*Question",
                Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
        Matcher m = p_groups.matcher(text);

        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String workOn = m.group(0);
            String[] lines = workOn.split("[\\n]");
            processECollegeTextGroup(pool, part, lines);
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);

        // remaining last text
        if (sb != null && sb.length() != 0) {
            if (sb.indexOf("Collapse Question") != -1) {
                String workOn = sb.substring(sb.indexOf("Collapse Question"));
                String[] lines = workOn.split("[\\n]");
                processECollegeTextGroup(pool, part, lines);
            }
        }

        try {
            assmt.getGrading().setGradebookIntegration(Boolean.TRUE);

            if (assmt.getParts().getTotalPoints().floatValue() <= 0) {
                assmt.setNeedsPoints(Boolean.FALSE);
            }

            assessmentService.saveAssessment(assmt);
        } catch (AssessmentPolicyException ep) {

        }
        this.poolService.savePool(pool);

    }
}

From source file:org.ejbca.ui.web.protocol.OCSPServlet.java

/**
 * Reads the request bytes and verifies min and max size of the request. If an error occurs it throws a MalformedRequestException. 
 * Can get request bytes both from a HTTP GET and POST request
 * //  w  ww  .  jav  a  2 s .c  o m
 * @param request
 * @param response
 * @return the request bytes or null if an error occured.
 * @throws IOException In case there is no stream to read
 * @throws MalformedRequestException 
 */
private byte[] checkAndGetRequestBytes(HttpServletRequest request, HttpMethod httpMethod)
        throws IOException, MalformedRequestException {
    final byte[] ret;
    // Get the request data
    final int n = request.getContentLength();
    // Expect n might be -1 for HTTP GET requests
    if (log.isDebugEnabled()) {
        log.debug(">checkAndGetRequestBytes. Received " + httpMethod.name() + " request with content length: "
                + n + " from " + request.getRemoteAddr());
    }
    if (n > LimitLengthASN1Reader.MAX_REQUEST_SIZE) {
        String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE, n);
        log.info(msg);
        throw new MalformedRequestException(msg);
    }
    // So we passed basic tests, now we can read the bytes, but still keep an eye on the size
    // we can not fully trust the sent content length.
    if (HttpMethod.POST.equals(httpMethod)) {
        final ServletInputStream in = request.getInputStream(); // ServletInputStream does not have to be closed, container handles this
        LimitLengthASN1Reader limitLengthASN1Reader = new LimitLengthASN1Reader(in, n);
        try {
            ret = limitLengthASN1Reader.readFirstASN1Object();
            if (n > ret.length) {
                // The client is sending more data than the OCSP request. It might be slightly broken or trying to bog down the server on purpose.
                // In the interest of not breaking existing systems that might have slightly broken clients we just log for a warning for now.
                String msg = intres.getLocalizedMessage("ocsp.additionaldata", ret.length, n);
                log.warn(msg);
            }
        } finally {
            limitLengthASN1Reader.close();
        }
    } else if (HttpMethod.GET.equals(httpMethod)) {
        // GET request
        final StringBuffer url = request.getRequestURL();
        // RFC2560 A.1.1 says that request longer than 255 bytes SHOULD be sent by POST, we support GET for longer requests anyway.
        if (url.length() <= LimitLengthASN1Reader.MAX_REQUEST_SIZE) {
            final String decodedRequest;
            try {
                // We have to extract the pathInfo manually, to avoid multiple slashes being converted to a single
                // According to RFC 2396 2.2 chars only have to encoded if they conflict with the purpose, so
                // we can for example expect both '/' and "%2F" in the request.
                final String fullServletpath = request.getContextPath() + request.getServletPath();
                final int paramIx = Math.max(url.indexOf(fullServletpath), 0) + fullServletpath.length() + 1;
                final String requestString = paramIx < url.length() ? url.substring(paramIx) : "";
                decodedRequest = URLDecoder.decode(requestString, "UTF-8").replaceAll(" ", "+");
            } catch (Exception e) {
                String msg = intres.getLocalizedMessage("ocsp.badurlenc");
                log.info(msg);
                throw new MalformedRequestException(e);
            }
            if (decodedRequest != null && decodedRequest.length() > 0) {
                if (log.isDebugEnabled()) {
                    // Don't log the request if it's too long, we don't want to cause denial of service by filling log files or buffers.
                    if (decodedRequest.length() < 2048) {
                        log.debug("decodedRequest: " + decodedRequest);
                    } else {
                        log.debug("decodedRequest too long to log: " + decodedRequest.length());
                    }
                }
                try {
                    ret = Base64.decode(decodedRequest.getBytes());
                } catch (Exception e) {
                    String msg = intres.getLocalizedMessage("ocsp.badurlenc");
                    log.info(msg);
                    throw new MalformedRequestException(e);
                }
            } else {
                String msg = intres.getLocalizedMessage("ocsp.missingreq");
                log.info(msg);
                throw new MalformedRequestException(msg);
            }
        } else {
            String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE,
                    url.length());
            log.info(msg);
            throw new MalformedRequestException(msg);
        }
    } else {
        // Strange, an unknown method
        String msg = intres.getLocalizedMessage("ocsp.unknownmethod", request.getMethod());
        log.info(msg);
        throw new MalformedRequestException(msg);
    }
    // Make a final check that we actually received something
    if (ret == null || ret.length == 0) {
        String msg = intres.getLocalizedMessage("ocsp.emptyreq", request.getRemoteAddr());
        log.info(msg);
        throw new MalformedRequestException(msg);
    }
    return ret;
}

From source file:org.opennms.ng.services.databaseschemaconfig.JdbcFilterDao.java

/**
 * Generic method to parse and translate a rule into SQL.
 *
 * Only columns listed in database-schema.xml may be used in a filter
 * (explicit "table.column" specification is not supported in filters)
 *
 * To differentiate column names from SQL key words (operators, functions, typecasts, etc)
 * SQL_KEYWORD_REGEX must match any SQL key words that may be used in filters,
 * and must not match any column names or prefixed values
 *
 * To make filter syntax more simple and intuitive than SQL
 * - Filters support some aliases for common SQL key words / operators
 *    "&amp;" or "&amp;&amp;" = "AND"
 *    "|" or "||" = "OR"//www .j  a  v a  2s .  com
 *    "!" = "NOT"
 *    "==" = "="
 * - "IPLIKE" may be used as an operator instead of a function in filters ("ipAddr IPLIKE '*.*.*.*'")
 *   When using "IPLIKE" as an operator, the value does not have to be quoted ("ipAddr IPLIKE *.*.*.*" is ok)
 * - Some common SQL expressions may be generated by adding a (lower-case) prefix to an unquoted value in the filter
 *    "isVALUE" = "serviceName = VALUE"
 *    "notisVALUE" = interface does not support the specified service
 *    "catincVALUE" = node is in the specified category
 * - Double-quoted (") strings in filters are converted to single-quoted (') strings in SQL
 *   SQL treats single-quoted strings as constants (values) and double-quoted strings as identifiers (columns, tables, etc)
 *   So, all quoted strings in filters are treated as constants, and filters don't support quoted identifiers
 *
 * This function does not do complete syntax/grammar checking - that is left to the database itself - do not assume the output is valid SQL
 *
 * @param tables
 *            a list to be populated with any tables referenced by the returned SQL
 * @param rule
 *            the rule to parse
 *
 * @return an SQL WHERE clause
 *
 * @throws org.opennms.ng.services.databaseschemaconfig.FilterParseException
 *             if any errors occur during parsing
 */
private String parseRule(final List<Table> tables, final String rule) throws FilterParseException {
    if (rule != null && rule.length() > 0) {
        final List<String> extractedStrings = new ArrayList<String>();

        String sqlRule = rule;

        // Extract quoted strings from rule and convert double-quoted strings to single-quoted strings
        // Quoted strings need to be extracted first to avoid accidentally matching/modifying anything within them
        // As in SQL, pairs of quotes within a quoted string are treated as an escaped quote character:
        //  'a''b' = a'b ; "a""b" = a"b ; 'a"b' = a"b ; "a'b" = a'b
        Matcher regex = SQL_QUOTE_PATTERN.matcher(sqlRule);
        StringBuffer tempStringBuff = new StringBuffer();
        while (regex.find()) {
            final String tempString = regex.group();
            if (tempString.charAt(0) == '"') {
                extractedStrings.add("'" + tempString.substring(1, tempString.length() - 1)
                        .replaceAll("\"\"", "\"").replaceAll("'", "''") + "'");
            } else {
                extractedStrings.add(regex.group());
            }
            regex.appendReplacement(tempStringBuff, "###@" + (extractedStrings.size() - 1) + "@###");
        }
        final int tempIndex = tempStringBuff.length();
        regex.appendTail(tempStringBuff);
        if (tempStringBuff.substring(tempIndex).indexOf('\'') > -1) {
            final String message = "Unmatched ' in filter rule '" + rule + "'";
            LOG.error(message);
            throw new FilterParseException(message);
        }
        if (tempStringBuff.substring(tempIndex).indexOf('"') > -1) {
            final String message = "Unmatched \" in filter rule '" + rule + "'";
            LOG.error(message);
            throw new FilterParseException(message);
        }
        sqlRule = tempStringBuff.toString();

        // Translate filter-specific operators to SQL operators
        sqlRule = sqlRule.replaceAll("\\s*(?:&|&&)\\s*", " AND ");
        sqlRule = sqlRule.replaceAll("\\s*(?:\\||\\|\\|)\\s*", " OR ");
        sqlRule = sqlRule.replaceAll("\\s*!(?!=)\\s*", " NOT ");
        sqlRule = sqlRule.replaceAll("==", "=");

        // Translate IPLIKE operators to IPLIKE() functions
        // If IPLIKE is already used as a function in the filter, this regex should not match it
        regex = SQL_IPLIKE_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            // Is the second argument already a quoted string?
            if (regex.group().charAt(0) == '#') {
                regex.appendReplacement(tempStringBuff, "IPLIKE($1, $2)");
            } else {
                regex.appendReplacement(tempStringBuff, "IPLIKE($1, '$2')");
            }
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Extract SQL key words to avoid identifying them as columns or prefixed values
        regex = SQL_KEYWORD_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            extractedStrings.add(regex.group().toUpperCase());
            regex.appendReplacement(tempStringBuff, "###@" + (extractedStrings.size() - 1) + "@###");
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Identify prefixed values and columns
        regex = SQL_VALUE_COLUMN_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            // Convert prefixed values to SQL expressions
            if (regex.group().startsWith("is")) {
                regex.appendReplacement(tempStringBuff,
                        addColumn(tables, "serviceName") + " = '" + regex.group().substring(2) + "'");
            } else if (regex.group().startsWith("notis")) {
                regex.appendReplacement(tempStringBuff, addColumn(tables, "ipAddr")
                        + " NOT IN (SELECT ifServices.ipAddr FROM ifServices, service WHERE service.serviceName ='"
                        + regex.group().substring(5) + "' AND service.serviceID = ifServices.serviceID)");
            } else if (regex.group().startsWith("catinc")) {
                regex.appendReplacement(tempStringBuff, addColumn(tables, "nodeID")
                        + " IN (SELECT category_node.nodeID FROM category_node, categories WHERE categories.categoryID = category_node.categoryID AND categories.categoryName = '"
                        + regex.group().substring(6) + "')");
            } else {
                // Call addColumn() on each column
                regex.appendReplacement(tempStringBuff, addColumn(tables, regex.group()));
            }
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();

        // Merge extracted strings back into expression
        regex = SQL_ESCAPED_PATTERN.matcher(sqlRule);
        tempStringBuff = new StringBuffer();
        while (regex.find()) {
            regex.appendReplacement(tempStringBuff,
                    Matcher.quoteReplacement(extractedStrings.get(Integer.parseInt(regex.group(1)))));
        }
        regex.appendTail(tempStringBuff);
        sqlRule = tempStringBuff.toString();
        return "WHERE " + sqlRule;
    }
    return "";
}

From source file:org.apache.ode.bpel.elang.xpath20.compiler.XPath20ExpressionCompilerImpl.java

/**
 * Returns the list of variable references in the given XPath expression
 * that may not have been resolved properly, which is the case especially
 * if the expression contains a function, which short circuited the evaluation.
 *
 * @param xpathStr//  w w w .  j  a  v a2s  . com
 * @return list of variable expressions that may not have been resolved properly
 */
private List<String> extractVariableExprs(String xpathStr) {
    ArrayList<String> variableExprs = new ArrayList<String>();
    int firstVariable = xpathStr.indexOf("$"), lastVariable = xpathStr.lastIndexOf("$"),
            firstFunction = xpathStr.indexOf("(");
    StringBuffer variableExpr = new StringBuffer();
    if ((firstVariable > 0 && // the xpath references a variable
            firstFunction > 0) || // the xpath contains a function
            (firstVariable < lastVariable)) { // the xpath references multiple variables
        // most likely, the variable reference has not been resolved, so make that happen
        boolean quoted = false, doubleQuoted = false, variable = false;
        Name11Checker nameChecker = Name11Checker.getInstance();
        for (int index = 0; index < xpathStr.length(); index++) {
            char ch = xpathStr.charAt(index);
            if (ch == '\'') {
                quoted = !quoted;
            }
            if (ch == '\"') {
                doubleQuoted = !doubleQuoted;
            }
            if (quoted || doubleQuoted) {
                continue;
            }
            if (ch == '$') {
                variable = true;
                variableExpr.setLength(0);
                variableExpr.append(ch);
            } else {
                if (variable) {
                    variableExpr.append(ch);
                    // in the name is qualified, don't check if its a qname when we're at the ":" character
                    if (ch == ':') {
                        continue;
                    }
                    if (index == xpathStr.length() || !nameChecker.isQName(variableExpr.substring(1))) {
                        variable = false;
                        variableExpr.setLength(variableExpr.length() - 1);
                        variableExprs.add(variableExpr.toString());
                        variableExpr.setLength(0);
                    }
                }
            }
        }
        if (variableExpr.length() > 0) {
            variableExprs.add(variableExpr.toString());
        }
    }
    return variableExprs;
}

From source file:com.flexoodb.engines.FlexJAXBMappedDBDataEngine.java

private Object merge(Object obj, Connection conn, String targettable) throws Exception {

    // check if the object has a table
    String tablename = (targettable == null ? ((FlexContainer) obj).getObject().getClass().getSimpleName()
            : targettable).toLowerCase();

    tablename = tablename.endsWith("type") ? tablename.substring(0, tablename.lastIndexOf("type")) : tablename;

    //FlexElement element = _elements.get(tablename);
    FlexElement element = null;//from  ww w.  ja  v a2 s .  c o  m
    if (tablename.indexOf("_") > -1) {
        element = _elements.get(tablename.substring(tablename.indexOf("_") + 1));
    } else {
        element = _elements.get(tablename);
    }

    String idcolumn = element.getAttribute("idcolumn").getValue();
    String realtablename = element.getAttribute("realtablename").getValue();
    String parentidcolumn = element.getAttribute("parentidcolumn").getValue();
    boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false
            : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true"));

    String id = ((FlexContainer) obj).getId();
    String parentid = ((FlexContainer) obj).getParentId();
    Object obj2 = ((FlexContainer) obj).getObject();

    FlexElement idelement = element.getElementByName(idcolumn);

    // get old record in database first
    PreparedStatement ps = (PreparedStatement) conn.prepareStatement(
            "select * from " + ((realtablename != null && !_shared) ? realtablename : tablename.toLowerCase())
                    + " where " + idcolumn + "=?");

    if (idelement.getType().equals("string")) {
        ps.setString(1, id);
    } else {
        ps.setInt(1, Integer.parseInt(id));
    }

    ResultSet res = ps.executeQuery();

    // check if a record was found
    if (res != null && res.next()) {

        Hashtable h = FlexUtils.getRDBMSRecordValues(res); // get available values in the original
        ps.close();

        _flexutils.softTransfer(h, obj2);

        Hashtable<String, Object[]> fieldswithcontent = getNonNullObjectFields(tablename, idcolumn,
                parentidcolumn, id, parentid, obj2, element);

        StringBuffer fields = new StringBuffer();

        Enumeration en = fieldswithcontent.keys();
        int i = 0;
        while (en.hasMoreElements()) {
            i++;
            String field = (String) en.nextElement();
            fields.append(",`" + field + "`=?");
        }

        i++;

        PreparedStatement ps2 = (PreparedStatement) conn.prepareStatement(
                "update " + ((realtablename != null && !_shared) ? realtablename : tablename.toLowerCase())
                        + " set " + fields.substring(1) + " where " + idcolumn + "=?");

        if (idelement.getType().equals("string")) {
            ps2.setString(i, id);
        } else {
            ps2.setInt(i, Integer.parseInt(id));
        }

        updatePreparedStatement(tablename, fieldswithcontent, ps2);

        ps2.executeUpdate();
        ps2.close();

    } else {
        throw new ObjectNotFoundException(
                "update error: " + ((realtablename != null) ? realtablename : tablename.toLowerCase())
                        + " with id:" + id + " does not exist.");
    }
    return obj;
}

From source file:gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCAdminComponentDAO.java

private String getDelimetedIdSeq(List idSeqList, String delimiter) {
    if (idSeqList == null || idSeqList.isEmpty()) {
        return "";
    }//from   ww w .j  a va  2  s .  c  o m

    StringBuffer sbuf = new StringBuffer();
    String delimted = null;
    Iterator it = idSeqList.iterator();
    while (it.hasNext()) {
        String idseq = (String) it.next();
        sbuf.append(delimiter).append("'").append(idseq).append("'");
    }
    //System.out.println("subString = "  + sbuf.substring(1) );
    return sbuf.substring(delimiter.length());
}

From source file:nl.nn.adapterframework.http.HttpSender.java

protected HttpMethod getMethod(URI uri, String message, ParameterValueList parameters,
        Map<String, String> headersParamsMap) throws SenderException {
    try {//from   w w w  .ja  va2s .c o m
        boolean queryParametersAppended = false;
        if (isEncodeMessages()) {
            message = URLEncoder.encode(message);
        }

        StringBuffer path = new StringBuffer(uri.getPath());
        if (!StringUtils.isEmpty(uri.getQuery())) {
            path.append("?" + uri.getQuery());
            queryParametersAppended = true;
        }

        if (getMethodType().equals("GET")) {
            if (parameters != null) {
                queryParametersAppended = appendParameters(queryParametersAppended, path, parameters,
                        headersParamsMap);
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "path after appending of parameters [" + path.toString() + "]");
            }
            GetMethod result = new GetMethod(path + (parameters == null ? message : ""));
            for (String param : headersParamsMap.keySet()) {
                result.addRequestHeader(param, headersParamsMap.get(param));
            }
            if (log.isDebugEnabled())
                log.debug(
                        getLogPrefix() + "HttpSender constructed GET-method [" + result.getQueryString() + "]");
            return result;
        } else if (getMethodType().equals("POST")) {
            PostMethod postMethod = new PostMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                postMethod.setRequestHeader("Content-Type", getContentType());
            }
            if (parameters != null) {
                StringBuffer msg = new StringBuffer(message);
                appendParameters(true, msg, parameters, headersParamsMap);
                if (StringUtils.isEmpty(message) && msg.length() > 1) {
                    message = msg.substring(1);
                } else {
                    message = msg.toString();
                }
            }
            for (String param : headersParamsMap.keySet()) {
                postMethod.addRequestHeader(param, headersParamsMap.get(param));
            }
            postMethod.setRequestBody(message);

            return postMethod;
        }
        if (getMethodType().equals("PUT")) {
            PutMethod putMethod = new PutMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                putMethod.setRequestHeader("Content-Type", getContentType());
            }
            if (parameters != null) {
                StringBuffer msg = new StringBuffer(message);
                appendParameters(true, msg, parameters, headersParamsMap);
                if (StringUtils.isEmpty(message) && msg.length() > 1) {
                    message = msg.substring(1);
                } else {
                    message = msg.toString();
                }
            }
            putMethod.setRequestBody(message);
            return putMethod;
        }
        if (getMethodType().equals("DELETE")) {
            DeleteMethod deleteMethod = new DeleteMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                deleteMethod.setRequestHeader("Content-Type", getContentType());
            }
            return deleteMethod;
        }
        if (getMethodType().equals("HEAD")) {
            HeadMethod headMethod = new HeadMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                headMethod.setRequestHeader("Content-Type", getContentType());
            }
            return headMethod;
        }
        if (getMethodType().equals("REPORT")) {
            Element element = XmlUtils.buildElement(message, true);
            ReportInfo reportInfo = new ReportInfo(element, 0);
            ReportMethod reportMethod = new ReportMethod(path.toString(), reportInfo);
            if (StringUtils.isNotEmpty(getContentType())) {
                reportMethod.setRequestHeader("Content-Type", getContentType());
            }
            return reportMethod;
        }
        throw new SenderException(
                "unknown methodtype [" + getMethodType() + "], must be either POST, GET, PUT or DELETE");
    } catch (URIException e) {
        throw new SenderException(getLogPrefix() + "cannot find path from url [" + getUrl() + "]", e);
    } catch (DavException e) {
        throw new SenderException(e);
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    } catch (IOException e) {
        throw new SenderException(e);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

public List<User> getPKUsersForIds(List<Long> ids) {
    if (ids.size() == 0) {
        return new ArrayList<User>(0);
    }/*from ww w  . ja  v  a  2 s  .co  m*/
    StringBuffer idStr = new StringBuffer();
    for (Long id : ids) {
        idStr.append("," + id);
    }
    String idList = idStr.substring(1);
    List<User> users = new ArrayList<User>(ids.size());
    String table = Contact.TABLE;
    String[] projection = new String[] { Contact.PERSON_ID, Contact.NAME, Contact.PUBLIC_KEY };
    String selection = Contact._ID + " in (" + idList + ")";
    String[] selectionArgs = null;
    String groupBy = null;
    String having = null;
    String orderBy = null;
    Cursor c = getReadableDatabase().query(table, projection, selection, selectionArgs, groupBy, having,
            orderBy);
    try {
        if (c.moveToFirst())
            do {
                users.add(new PKUser(c.getString(0), c.getString(1), c.getString(2)));
            } while (c.moveToNext());
        return users;
    } finally {
        c.close();
    }
}