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:edu.stanford.mobisocial.dungbeetle.DBHelper.java

private long getFeedLastVisibleId(String feedName) {
    String[] types = DbObjects.getRenderableTypes();
    StringBuffer allowed = new StringBuffer();
    for (String type : types) {
        allowed.append(",'").append(type).append("'");
    }/* w ww  .j  ava2  s .  c om*/
    String visibleTypes = DbObject.TYPE + " in (" + allowed.substring(1) + ")";
    String selection = DbObject.FEED_NAME + " = ?";

    selection = andClauses(selection, visibleTypes);
    Cursor c = getReadableDatabase().query(DbObject.TABLE, new String[] { DbObject._ID }, selection,
            new String[] { feedName }, null, null, DbObject.SEQUENCE_ID + " DESC LIMIT 1");
    try {
        c.moveToFirst();
        if (!c.isAfterLast()) {
            long max = c.getLong(0);
            return max;
        }
        return -1;
    } finally {
        c.close();
    }
}

From source file:org.ejbca.ui.web.protocol.OCSPServletBase.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
 * /*www. j  ava  2 s. co  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)
        throws IOException, MalformedRequestException {
    final byte[] ret;
    // Get the request data
    String method = request.getMethod();
    String remoteAddress = request.getRemoteAddr();
    final int n = request.getContentLength();
    if (m_log.isDebugEnabled()) {
        m_log.debug(">checkAndGetRequestBytes. Received " + method + " request with content length: " + n
                + " from " + remoteAddress);
    }
    if (n > LimitLengthASN1Reader.MAX_REQUEST_SIZE) {
        String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE, n);
        m_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 (StringUtils.equals(method, "POST")) {
        final ServletInputStream in = request.getInputStream(); // ServletInputStream does not have to be closed, container handles this
        ret = new LimitLengthASN1Reader(in, n).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);
            m_log.warn(msg);
            //throw new MalformedRequestException(msg);   // Responding with MALFORMED_REQUEST. 
        }
    } else if (StringUtils.equals(method, "GET")) {
        // 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(" ", "+");
                //                  if (m_log.isDebugEnabled()) {
                //                     m_log.debug("URL: "+url.toString());
                //                  }
            } catch (Exception e) {
                String msg = intres.getLocalizedMessage("ocsp.badurlenc");
                m_log.info(msg);
                throw new MalformedRequestException(e);
            }
            if (decodedRequest != null && decodedRequest.length() > 0) {
                if (m_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) {
                        m_log.debug("decodedRequest: " + decodedRequest);
                    } else {
                        m_log.debug("decodedRequest too long to log: " + decodedRequest.length());
                    }
                }
                try {
                    ret = org.ejbca.util.Base64.decode(decodedRequest.getBytes());
                } catch (Exception e) {
                    String msg = intres.getLocalizedMessage("ocsp.badurlenc");
                    m_log.info(msg);
                    throw new MalformedRequestException(e);
                }
            } else {
                String msg = intres.getLocalizedMessage("ocsp.missingreq");
                m_log.info(msg);
                throw new MalformedRequestException(msg);
            }
        } else {
            String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE,
                    url.length());
            m_log.info(msg);
            throw new MalformedRequestException(msg);
        }
    } else {
        // Strange, an unknown method
        String msg = intres.getLocalizedMessage("ocsp.unknownmethod", method);
        m_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", remoteAddress);
        m_log.info(msg);
        throw new MalformedRequestException(msg);
    }
    return ret;
}

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

private Object persist(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;

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

    // retrieve the methods of the object and use as param.

    FlexElement element = null;/*  w w w. ja v  a 2s  .co  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();
    String autoincrement = element.getAttribute("autoincrement").getValue();
    boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false
            : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true"));

    if (!autoincrement.equalsIgnoreCase("true")) {
        if (id == null || id.isEmpty()) {
            id = getNewId();
            FlexUtils.setId(id, (FlexContainer) obj);
        }

        if (parentid == null || parentid.isEmpty()) {
            ((FlexContainer) obj).setParentId(id);
        }
    }

    StringBuffer fields = new StringBuffer();
    StringBuffer entries = new StringBuffer();

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

    Enumeration en = fieldswithcontent.keys();
    while (en.hasMoreElements()) {
        String field = (String) en.nextElement();
        //boolean ok = true;
        fields.append(",`" + field + "`");
        entries.append(",?");
    }

    //System.out.println(">>>insert into "+tablename.toLowerCase()+" ("+fields.substring(1)+") values ("+entries.substring(1)+")");
    PreparedStatement ps = null;

    if (autoincrement.equalsIgnoreCase("true")) {
        ps = (PreparedStatement) conn.prepareStatement(
                "insert into " + ((realtablename != null && !_shared) ? realtablename : tablename.toLowerCase())
                        + " (" + fields.substring(1) + ") values (" + entries.substring(1) + ")",
                Statement.RETURN_GENERATED_KEYS);
        // then we get the preparedstatement
        updatePreparedStatement(tablename, fieldswithcontent, ps);
        ps.executeUpdate();
        ResultSet keys = ps.getGeneratedKeys();
        keys.next();

        int newkey = keys.getInt(1);

        keys.close();

        FlexUtils.setId(newkey + "", (FlexContainer) obj);

        if (parentid == null || parentid.isEmpty()) {
            ((FlexContainer) obj).setParentId(newkey + "");
        }

        FlexUtils.setObjectMethod(((FlexContainer) obj).getObject(), idcolumn, new BigInteger(newkey + ""));

    } else {
        ps = (PreparedStatement) conn.prepareStatement(
                "insert into " + ((realtablename != null && !_shared) ? realtablename : tablename.toLowerCase())
                        + " (" + fields.substring(1) + ") values (" + entries.substring(1) + ")");
        // then we get the preparedstatement
        updatePreparedStatement(tablename, fieldswithcontent, ps);
        ps.executeUpdate();
    }

    ps.close();

    return obj;
}

From source file:pl.touk.xmlbeansxx.ClassGen.java

String nsClassName(SchemaType sType) {
    StringTokenizer t = new StringTokenizer(getFullJavaName(sType), ".");
    StringBuffer b = new StringBuffer();
    String last = "";
    while (t.hasMoreTokens()) {
        b.append(last);/*from w  w w . j ava2  s. c  om*/
        last = "::" + t.nextToken();
    }
    if (b.length() == 0)
        b.append("::");
    return b.substring(2);
}

From source file:org.medici.bia.common.util.HtmlUtils.java

/**
 * /*from   ww  w .j a va2s.com*/
 * @param text
 * @param searchWord
 * @return
 */
public static String highlightText(String text, String searchWord) {
    StringBuffer returnText = new StringBuffer(text);
    Integer indexWord = new Integer(0);
    List<String> exactWords = new ArrayList<String>();
    String toSearch = searchWord;
    //MD: This code is to identify the words between double quotes
    while (toSearch.contains("\"")) {
        //First double quote
        int from = toSearch.indexOf('\"');
        //Second double quote
        int to = toSearch.indexOf('\"', from + 1);
        //If there is the second double quote or not
        if (to != -1) {
            //Add the exact words to the list and remove them from the string
            exactWords.add(toSearch.substring(from + 1, to).toLowerCase());
            toSearch = toSearch.substring(0, from) + toSearch.substring(to + 1, toSearch.length());
        } else {
            toSearch = toSearch.replace("\"", " ");
        }
    }
    String[] words = StringUtils.split(searchWord.toLowerCase(), " ");
    if (exactWords.size() == 0) {
        for (String currentWord : words) {
            indexWord = returnText.toString().toLowerCase().indexOf(currentWord);
            while (indexWord != -1) {
                while (indexWord >= 0 && returnText.charAt(indexWord) != ' ') {
                    indexWord--;
                }
                Integer beginWord = indexWord + 1;
                returnText.insert(beginWord, "<span class='highlighted'>");
                Integer endWord = beginWord + 26;
                while (endWord < returnText.length() && returnText.charAt(endWord) != ' ') {
                    endWord++;
                }
                returnText.insert(endWord, "</span>");
                Integer nextWord = returnText.substring(endWord).toLowerCase().indexOf(currentWord);
                if (nextWord != -1) {
                    indexWord = endWord + nextWord;
                } else {
                    indexWord = nextWord;
                }
            }
        }
    } else {
        for (String currentWord : exactWords) {
            indexWord = returnText.toString().toLowerCase().indexOf(currentWord);
            while (indexWord != -1) {
                Integer beginWord = indexWord;
                returnText.insert(beginWord, "<span class='highlighted'>");
                Integer endWord = beginWord + 26 + currentWord.length();
                returnText.insert(endWord, "</span>");
                Integer nextWord = returnText.substring(endWord).toLowerCase().indexOf(currentWord);
                if (nextWord != -1) {
                    indexWord = endWord + nextWord;
                } else {
                    indexWord = nextWord;
                }
            }
        }
    }
    return returnText.toString();
}

From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java

private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException {
    shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT);
    try {//from  w  w  w .  j  ava2  s .  co m
        shuttle.sharedScope = context.getSharedScope();

        String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port);
        Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain);
        if (!shouldRewrite(domain)) {
            Engine.logSiteClipper.info(
                    "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector");
            shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "The domain " + domain + " is not allowed with this connector");
            return;
        }

        String uri = shuttle.getRequest(QueryPart.uri);

        Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl());

        HttpMethod httpMethod = null;
        XulRecorder xulRecorder = context.getXulRecorder();
        if (xulRecorder != null) {
            httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery());
        }
        if (httpMethod == null) {
            try {
                switch (shuttle.getRequestHttpMethodType()) {
                case GET:
                    httpMethod = new GetMethod(uri);
                    break;
                case POST:
                    httpMethod = new PostMethod(uri);
                    ((PostMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case PUT:
                    httpMethod = new PutMethod(uri);
                    ((PutMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case DELETE:
                    httpMethod = new DeleteMethod(uri);
                    break;
                case HEAD:
                    httpMethod = new HeadMethod(uri);
                    break;
                case OPTIONS:
                    httpMethod = new OptionsMethod(uri);
                    break;
                case TRACE:
                    httpMethod = new TraceMethod(uri);
                    break;
                default:
                    throw new ServletException(
                            "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod());
                }
                httpMethod.setFollowRedirects(false);
            } catch (Exception e) {
                throw new ServletException(
                        "(SiteClipperConnector) unexpected exception will building the http method : "
                                + e.getMessage());
            }
            shuttle.httpMethod = httpMethod;

            SiteClipperScreenClass screenClass = getCurrentScreenClass();
            Engine.logSiteClipper.info("Request screen class: " + screenClass.getName());

            for (String name : Collections
                    .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) {
                if (requestHeadersToIgnore.contains(HeaderName.parse(name))) {
                    Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name);
                } else {
                    String value = shuttle.request.getHeader(name);
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) Copying request header " + name + "=" + value);
                    shuttle.setRequestCustomHeader(name, value);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass "
                    + screenClass.getName());
            for (IRequestRule rule : screenClass.getRequestRules()) {
                if (rule.isEnabled()) {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) applying request rule " + rule.getName());
                    rule.fireEvents();
                    boolean done = rule.applyOnRequest(shuttle);
                    Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName()
                            + " is " + (done ? "well" : "not") + " applied");
                } else {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName());
                }
            }

            for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey()
                        + "=" + header.getValue());
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }

            String queryString = shuttle.request.getQueryString();

            if (queryString != null) {
                try {
                    // Fake test in order to check query string validity
                    new URI("http://localhost/index?" + queryString, true,
                            httpMethod.getParams().getUriCharset());
                } catch (URIException e) {
                    // Bugfix #2103
                    StringBuffer newQuery = new StringBuffer();
                    for (String part : RegexpUtils.pattern_and.split(queryString)) {
                        String[] pair = RegexpUtils.pattern_equals.split(part, 2);
                        try {
                            newQuery.append('&')
                                    .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8"));
                            if (pair.length > 1) {
                                newQuery.append('=').append(
                                        URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8"));
                            }
                        } catch (UnsupportedEncodingException ee) {
                            Engine.logSiteClipper
                                    .trace("(SiteClipperConnector) failed to encode query part : " + part);
                        }
                    }

                    queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString();
                    Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString);
            httpMethod.setQueryString(queryString);

            //            if (context.httpState == null) {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID);
            //               context.httpState = new HttpState();
            //            } else {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID);
            //            }

            getHttpState(shuttle);

            HostConfiguration hostConfiguration = getHostConfiguration(shuttle);

            HttpMethodParams httpMethodParams = httpMethod.getParams();
            httpMethodParams.setBooleanParameter("http.connection.stalecheck", true);
            httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, true));

            Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " "
                    + hostConfiguration.getHostURL() + httpMethod.getURI().toString());

            HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool());
            HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool());
            httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState);
        } else {
            Engine.logSiteClipper.info("Retrieve recorded response from Context");
        }

        int status = httpMethod.getStatusCode();

        shuttle.processState = ProcessState.response;

        Engine.logSiteClipper.info("Request terminated with status " + status);
        shuttle.response.setStatus(status);

        if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK
                && shuttle.getResponseMimeType().startsWith("text/")) {
            fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString()));
        }

        SiteClipperScreenClass screenClass = getCurrentScreenClass();
        Engine.logSiteClipper.info("Response screen class: " + screenClass.getName());

        if (Engine.isStudioMode()) {
            Engine.theApp.fireObjectDetected(new EngineEvent(screenClass));
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            String name = header.getName();
            if (responseHeadersToIgnore.contains(HeaderName.parse(name))) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name);
            } else {
                String value = header.getValue();
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Copying response header " + name + "=" + value);
                shuttle.responseCustomHeaders.put(name, value);
            }
        }

        Engine.logSiteClipper.debug(
                "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName());
        for (IResponseRule rule : screenClass.getResponseRules()) {
            if (rule.isEnabled()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName());
                rule.fireEvents();
                boolean done = rule.applyOnResponse(shuttle);
                Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName()
                        + " is " + (done ? "well" : "not") + " applied");
            } else {
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName());
            }
        }

        for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) {
            Engine.logSiteClipper.trace(
                    "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue());
            shuttle.response.addHeader(header.getKey(), header.getValue());
        }

        if (shuttle.postInstructions != null) {
            JSONArray instructions = new JSONArray();
            for (IClientInstruction instruction : shuttle.postInstructions) {
                try {
                    instructions.put(instruction.getInstruction());
                } catch (JSONException e) {
                    Engine.logSiteClipper.error(
                            "(SiteClipperConnector) Failed to add a post instruction due to a JSONException",
                            e);
                }
            }
            String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n"
                    + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/jquery.min.js\"></script>\n" + "<script src=\""
                    + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/siteclipper.js\"></script>\n";

            String content = shuttle.getResponseAsString();
            Matcher matcher = HtmlLocation.head_top.matcher(content);
            String newContent = RegexpUtils.inject(matcher, codeToInject);
            if (newContent == null) {
                matcher = HtmlLocation.body_top.matcher(content);
                newContent = RegexpUtils.inject(matcher, codeToInject);
            }
            if (newContent != null) {
                shuttle.setResponseAsString(newContent);
            } else {
                Engine.logSiteClipper.info(
                        "(SiteClipperConnector) Failed to find a head or body tag in the response content");
                Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\"");
            }
        }

        long nbBytes = 0L;
        if (shuttle.responseAsString != null
                && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) {
            OutputStream os = shuttle.response.getOutputStream();
            switch (shuttle.getResponseContentEncoding()) {
            case gzip:
                os = new GZIPOutputStream(os);
                break;
            case deflate:
                os = new DeflaterOutputStream(os,
                        new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
                break;
            default:
                break;
            }
            nbBytes = shuttle.responseAsByte.length;
            IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset());
            os.close();
        } else {
            InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream()
                    : new ByteArrayInputStream(shuttle.responseAsByte);
            if (is != null) {
                nbBytes = 0;
                OutputStream os = shuttle.response.getOutputStream();
                int read = is.read();
                while (read >= 0) {
                    os.write(read);
                    os.flush();
                    read = is.read();
                    nbBytes++;
                }
                is.close();
                //               nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream());
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)");
            }
        }
        shuttle.response.getOutputStream().close();

        shuttle.score = getScore(nbBytes);
        Engine.logSiteClipper
                .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score);
    } finally {
        long duration = context.statistics.stop(shuttle.statisticsTaskID);
        if (context.requestedObject != null) {
            try {
                Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration),
                        Long.valueOf(shuttle.score));
            } catch (Exception e) {
                Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
    }
}

From source file:org.dspace.discovery.SolrServiceImpl.java

/**
 * Build a Lucene document for a DSpace Item and write the index
 *
 * @param context Users Context//  w ww .  j  av  a 2 s .  c o m
 * @param item    The DSpace Item to be indexed
 * @throws SQLException
 * @throws IOException
 */
protected void buildDocument(Context context, Item item) throws SQLException, IOException {
    String handle = item.getHandle();

    if (handle == null) {
        handle = HandleManager.findHandle(context, item);
    }

    // get the location string (for searching by collection & community)
    List<String> locations = getItemLocations(item);

    SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle, locations);

    log.debug("Building Item: " + handle);

    doc.addField("withdrawn", item.isWithdrawn());
    doc.addField("discoverable", item.isDiscoverable());

    //Keep a list of our sort values which we added, sort values can only be added once
    List<String> sortFieldsAdded = new ArrayList<String>();
    Set<String> hitHighlightingFields = new HashSet<String>();
    try {
        List<DiscoveryConfiguration> discoveryConfigurations = SearchUtils.getAllDiscoveryConfigurations(item);

        //A map used to save each sidebarFacet config by the metadata fields
        Map<String, List<DiscoverySearchFilter>> searchFilters = new HashMap<String, List<DiscoverySearchFilter>>();
        Map<String, DiscoverySortFieldConfiguration> sortFields = new HashMap<String, DiscoverySortFieldConfiguration>();
        Map<String, DiscoveryRecentSubmissionsConfiguration> recentSubmissionsConfigurationMap = new HashMap<String, DiscoveryRecentSubmissionsConfiguration>();
        Set<String> moreLikeThisFields = new HashSet<String>();
        for (DiscoveryConfiguration discoveryConfiguration : discoveryConfigurations) {
            for (int i = 0; i < discoveryConfiguration.getSearchFilters().size(); i++) {
                DiscoverySearchFilter discoverySearchFilter = discoveryConfiguration.getSearchFilters().get(i);
                for (int j = 0; j < discoverySearchFilter.getMetadataFields().size(); j++) {
                    String metadataField = discoverySearchFilter.getMetadataFields().get(j);
                    List<DiscoverySearchFilter> resultingList;
                    if (searchFilters.get(metadataField) != null) {
                        resultingList = searchFilters.get(metadataField);
                    } else {
                        //New metadata field, create a new list for it
                        resultingList = new ArrayList<DiscoverySearchFilter>();
                    }
                    resultingList.add(discoverySearchFilter);

                    searchFilters.put(metadataField, resultingList);
                }
            }

            DiscoverySortConfiguration sortConfiguration = discoveryConfiguration.getSearchSortConfiguration();
            if (sortConfiguration != null) {
                for (DiscoverySortFieldConfiguration discoverySortConfiguration : sortConfiguration
                        .getSortFields()) {
                    sortFields.put(discoverySortConfiguration.getMetadataField(), discoverySortConfiguration);
                }
            }

            DiscoveryRecentSubmissionsConfiguration recentSubmissionConfiguration = discoveryConfiguration
                    .getRecentSubmissionConfiguration();
            if (recentSubmissionConfiguration != null) {
                recentSubmissionsConfigurationMap.put(recentSubmissionConfiguration.getMetadataSortField(),
                        recentSubmissionConfiguration);
            }

            DiscoveryHitHighlightingConfiguration hitHighlightingConfiguration = discoveryConfiguration
                    .getHitHighlightingConfiguration();
            if (hitHighlightingConfiguration != null) {
                List<DiscoveryHitHighlightFieldConfiguration> fieldConfigurations = hitHighlightingConfiguration
                        .getMetadataFields();
                for (DiscoveryHitHighlightFieldConfiguration fieldConfiguration : fieldConfigurations) {
                    hitHighlightingFields.add(fieldConfiguration.getField());
                }
            }
            DiscoveryMoreLikeThisConfiguration moreLikeThisConfiguration = discoveryConfiguration
                    .getMoreLikeThisConfiguration();
            if (moreLikeThisConfiguration != null) {
                for (String metadataField : moreLikeThisConfiguration.getSimilarityMetadataFields()) {
                    moreLikeThisFields.add(metadataField);
                }
            }
        }

        List<String> toProjectionFields = new ArrayList<String>();
        String projectionFieldsString = new DSpace().getConfigurationService()
                .getProperty("discovery.index.projection");
        if (projectionFieldsString != null) {
            if (projectionFieldsString.indexOf(",") != -1) {
                for (int i = 0; i < projectionFieldsString.split(",").length; i++) {
                    toProjectionFields.add(projectionFieldsString.split(",")[i].trim());
                }
            } else {
                toProjectionFields.add(projectionFieldsString);
            }
        }

        DCValue[] mydc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
        for (DCValue meta : mydc) {
            String field = meta.schema + "." + meta.element;
            String unqualifiedField = field;

            String value = meta.value;

            if (value == null) {
                continue;
            }

            if (meta.qualifier != null && !meta.qualifier.trim().equals("")) {
                field += "." + meta.qualifier;
            }

            List<String> toIgnoreMetadataFields = SearchUtils.getIgnoredMetadataFields(item.getType());
            //We are not indexing provenance, this is useless
            if (toIgnoreMetadataFields != null && (toIgnoreMetadataFields.contains(field)
                    || toIgnoreMetadataFields.contains(unqualifiedField + "." + Item.ANY))) {
                continue;
            }

            String authority = null;
            String preferedLabel = null;
            List<String> variants = null;
            boolean isAuthorityControlled = MetadataAuthorityManager.getManager()
                    .isAuthorityControlled(meta.schema, meta.element, meta.qualifier);

            int minConfidence = isAuthorityControlled
                    ? MetadataAuthorityManager.getManager().getMinConfidence(meta.schema, meta.element,
                            meta.qualifier)
                    : Choices.CF_ACCEPTED;

            if (isAuthorityControlled && meta.authority != null && meta.confidence >= minConfidence) {
                boolean ignoreAuthority = new DSpace().getConfigurationService().getPropertyAsType(
                        "discovery.index.authority.ignore." + field, new DSpace().getConfigurationService()
                                .getPropertyAsType("discovery.index.authority.ignore", new Boolean(false)),
                        true);
                if (!ignoreAuthority) {
                    authority = meta.authority;

                    boolean ignorePrefered = new DSpace().getConfigurationService()
                            .getPropertyAsType("discovery.index.authority.ignore-prefered." + field,
                                    new DSpace().getConfigurationService().getPropertyAsType(
                                            "discovery.index.authority.ignore-prefered", new Boolean(false)),
                                    true);
                    if (!ignorePrefered) {

                        preferedLabel = ChoiceAuthorityManager.getManager().getLabel(meta.schema, meta.element,
                                meta.qualifier, meta.authority, meta.language);
                    }

                    boolean ignoreVariants = new DSpace().getConfigurationService()
                            .getPropertyAsType("discovery.index.authority.ignore-variants." + field,
                                    new DSpace().getConfigurationService().getPropertyAsType(
                                            "discovery.index.authority.ignore-variants", new Boolean(false)),
                                    true);
                    if (!ignoreVariants) {
                        variants = ChoiceAuthorityManager.getManager().getVariants(meta.schema, meta.element,
                                meta.qualifier, meta.authority, meta.language);
                    }

                }
            }

            if ((searchFilters.get(field) != null
                    || searchFilters.get(unqualifiedField + "." + Item.ANY) != null)) {
                List<DiscoverySearchFilter> searchFilterConfigs = searchFilters.get(field);
                if (searchFilterConfigs == null) {
                    searchFilterConfigs = searchFilters.get(unqualifiedField + "." + Item.ANY);
                }

                for (DiscoverySearchFilter searchFilter : searchFilterConfigs) {
                    Date date = null;
                    String separator = new DSpace().getConfigurationService()
                            .getProperty("discovery.solr.facets.split.char");
                    if (separator == null) {
                        separator = FILTER_SEPARATOR;
                    }
                    if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
                        //For our search filters that are dates we format them properly
                        date = toDate(value);
                        if (date != null) {
                            //TODO: make this date format configurable !
                            value = DateFormatUtils.formatUTC(date, "yyyy-MM-dd");
                        }
                    }
                    doc.addField(searchFilter.getIndexFieldName(), value);
                    doc.addField(searchFilter.getIndexFieldName() + "_keyword", value);

                    if (authority != null && preferedLabel == null) {
                        doc.addField(searchFilter.getIndexFieldName() + "_keyword",
                                value + AUTHORITY_SEPARATOR + authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_authority", authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_acid",
                                value.toLowerCase() + separator + value + AUTHORITY_SEPARATOR + authority);
                    }

                    if (preferedLabel != null) {
                        doc.addField(searchFilter.getIndexFieldName(), preferedLabel);
                        doc.addField(searchFilter.getIndexFieldName() + "_keyword", preferedLabel);
                        doc.addField(searchFilter.getIndexFieldName() + "_keyword",
                                preferedLabel + AUTHORITY_SEPARATOR + authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_authority", authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_acid", preferedLabel.toLowerCase()
                                + separator + preferedLabel + AUTHORITY_SEPARATOR + authority);
                    }
                    if (variants != null) {
                        for (String var : variants) {
                            doc.addField(searchFilter.getIndexFieldName() + "_keyword", var);
                            doc.addField(searchFilter.getIndexFieldName() + "_acid",
                                    var.toLowerCase() + separator + var + AUTHORITY_SEPARATOR + authority);
                        }
                    }

                    //Add a dynamic fields for auto complete in search
                    doc.addField(searchFilter.getIndexFieldName() + "_ac",
                            value.toLowerCase() + separator + value);
                    if (preferedLabel != null) {
                        doc.addField(searchFilter.getIndexFieldName() + "_ac",
                                preferedLabel.toLowerCase() + separator + preferedLabel);
                    }
                    if (variants != null) {
                        for (String var : variants) {
                            doc.addField(searchFilter.getIndexFieldName() + "_ac",
                                    var.toLowerCase() + separator + var);
                        }
                    }

                    if (searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET)) {
                        if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) {
                            //Add a special filter
                            //We use a separator to split up the lowercase and regular case, this is needed to get our filters in regular case
                            //Solr has issues with facet prefix and cases
                            if (authority != null) {
                                String facetValue = preferedLabel != null ? preferedLabel : value;
                                doc.addField(searchFilter.getIndexFieldName() + "_filter",
                                        facetValue.toLowerCase() + separator + facetValue + AUTHORITY_SEPARATOR
                                                + authority);
                            } else {
                                doc.addField(searchFilter.getIndexFieldName() + "_filter",
                                        value.toLowerCase() + separator + value);
                            }
                        } else if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
                            if (date != null) {
                                String indexField = searchFilter.getIndexFieldName() + ".year";
                                doc.addField(searchFilter.getIndexFieldName() + "_keyword",
                                        DateFormatUtils.formatUTC(date, "yyyy"));
                                doc.addField(indexField, DateFormatUtils.formatUTC(date, "yyyy"));
                                //Also save a sort value of this year, this is required for determining the upper & lower bound year of our facet
                                if (doc.getField(indexField + "_sort") == null) {
                                    //We can only add one year so take the first one
                                    doc.addField(indexField + "_sort", DateFormatUtils.formatUTC(date, "yyyy"));
                                }
                            }
                        } else if (searchFilter.getType()
                                .equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) {
                            HierarchicalSidebarFacetConfiguration hierarchicalSidebarFacetConfiguration = (HierarchicalSidebarFacetConfiguration) searchFilter;
                            String[] subValues = value
                                    .split(hierarchicalSidebarFacetConfiguration.getSplitter());
                            if (hierarchicalSidebarFacetConfiguration.isSkipFirstNodeLevel()
                                    && 1 < subValues.length) {
                                //Remove the first element of our array
                                subValues = (String[]) ArrayUtils.subarray(subValues, 1, subValues.length);
                            }
                            for (int i = 0; i < subValues.length; i++) {
                                StringBuilder valueBuilder = new StringBuilder();
                                for (int j = 0; j <= i; j++) {
                                    valueBuilder.append(subValues[j]);
                                    if (j < i) {
                                        valueBuilder
                                                .append(hierarchicalSidebarFacetConfiguration.getSplitter());
                                    }
                                }

                                String indexValue = valueBuilder.toString().trim();
                                doc.addField(searchFilter.getIndexFieldName() + "_tax_" + i + "_filter",
                                        indexValue.toLowerCase() + separator + indexValue);
                                //We add the field x times that it has occurred
                                for (int j = i; j < subValues.length; j++) {
                                    doc.addField(searchFilter.getIndexFieldName() + "_filter",
                                            indexValue.toLowerCase() + separator + indexValue);
                                    doc.addField(searchFilter.getIndexFieldName() + "_keyword", indexValue);
                                }
                            }
                        }
                    }
                }
            }

            if ((sortFields.get(field) != null || recentSubmissionsConfigurationMap.get(field) != null)
                    && !sortFieldsAdded.contains(field)) {
                //Only add sort value once
                String type;
                if (sortFields.get(field) != null) {
                    type = sortFields.get(field).getType();
                } else {
                    type = recentSubmissionsConfigurationMap.get(field).getType();
                }

                if (type.equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
                    Date date = toDate(value);
                    if (date != null) {
                        doc.addField(field + "_dt", date);
                    } else {
                        log.warn("Error while indexing sort date field, item: " + item.getHandle()
                                + " metadata field: " + field + " date value: " + date);
                    }
                } else {
                    doc.addField(field + "_sort", value);
                }
                sortFieldsAdded.add(field);
            }

            if (hitHighlightingFields.contains(field) || hitHighlightingFields.contains("*")
                    || hitHighlightingFields.contains(unqualifiedField + "." + Item.ANY)) {
                doc.addField(field + "_hl", value);
            }

            if (moreLikeThisFields.contains(field)
                    || moreLikeThisFields.contains(unqualifiedField + "." + Item.ANY)) {
                doc.addField(field + "_mlt", value);
            }

            doc.addField(field, value);
            if (toProjectionFields.contains(field)
                    || toProjectionFields.contains(unqualifiedField + "." + Item.ANY)) {
                StringBuffer variantsToStore = new StringBuffer();
                if (variants != null) {
                    for (String var : variants) {
                        variantsToStore.append(VARIANTS_STORE_SEPARATOR);
                        variantsToStore.append(var);
                    }
                }
                doc.addField(field + "_stored", value + STORE_SEPARATOR + preferedLabel + STORE_SEPARATOR
                        + (variantsToStore.length() > VARIANTS_STORE_SEPARATOR.length()
                                ? variantsToStore.substring(VARIANTS_STORE_SEPARATOR.length())
                                : "null")
                        + STORE_SEPARATOR + authority + STORE_SEPARATOR + meta.language);
            }

            if (meta.language != null && !meta.language.trim().equals("")) {
                String langField = field + "." + meta.language;
                doc.addField(langField, value);
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    log.debug("  Added Metadata");

    try {

        DCValue[] values = item.getMetadata("dc.relation.ispartof");

        if (values != null && values.length > 0 && values[0] != null && values[0].value != null) {
            // group on parent
            String handlePrefix = ConfigurationManager.getProperty("handle.canonical.prefix");
            if (handlePrefix == null || handlePrefix.length() == 0) {
                handlePrefix = "http://hdl.handle.net/";
            }

            doc.addField("publication_grp", values[0].value.replaceFirst(handlePrefix, ""));

        } else {
            // group on self
            doc.addField("publication_grp", item.getHandle());
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    log.debug("  Added Grouping");

    Vector<InputStreamReader> readers = new Vector<InputStreamReader>();

    try {
        // now get full text of any bitstreams in the TEXT bundle
        // trundle through the bundles
        Bundle[] myBundles = item.getBundles();

        for (Bundle myBundle : myBundles) {
            if ((myBundle.getName() != null) && myBundle.getName().equals("TEXT")) {
                // a-ha! grab the text out of the bitstreams
                Bitstream[] myBitstreams = myBundle.getBitstreams();

                for (Bitstream myBitstream : myBitstreams) {
                    try {
                        InputStreamReader is = new InputStreamReader(myBitstream.retrieve()); // get input
                        readers.add(is);

                        // Add each InputStream to the Indexed Document
                        String value = IOUtils.toString(is);
                        doc.addField("fulltext", value);

                        if (hitHighlightingFields.contains("*") || hitHighlightingFields.contains("fulltext")) {
                            doc.addField("fulltext_hl", value);
                        }

                        log.debug("  Added BitStream: " + myBitstream.getStoreNumber() + "   "
                                + myBitstream.getSequenceID() + "   " + myBitstream.getName());

                    } catch (Exception e) {
                        // this will never happen, but compiler is now
                        // happy.
                        log.trace(e.getMessage(), e);
                    }
                }
            }
        }
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
    } finally {
        Iterator<InputStreamReader> itr = readers.iterator();
        while (itr.hasNext()) {
            InputStreamReader reader = itr.next();
            if (reader != null) {
                reader.close();
            }
        }
        log.debug("closed " + readers.size() + " readers");
    }

    //Do any additional indexing, depends on the plugins
    List<SolrServiceIndexPlugin> solrServiceIndexPlugins = new DSpace().getServiceManager()
            .getServicesByType(SolrServiceIndexPlugin.class);
    for (SolrServiceIndexPlugin solrServiceIndexPlugin : solrServiceIndexPlugins) {
        solrServiceIndexPlugin.additionalIndex(context, item, doc);
    }

    // write the index and close the inputstreamreaders
    try {
        writeDocument(doc);
        log.info("Wrote Item: " + handle + " to Index");
    } catch (RuntimeException e) {
        log.error("Error while writing item to discovery index: " + handle + " message:" + e.getMessage(), e);
    }
}

From source file:org.apache.axis.transport.http.SimpleAxisWorker.java

/**
 * The main workhorse method.//from  w w w.j  a v  a 2s.c o m
 */
public void execute() {
    byte buf[] = new byte[BUFSIZ];
    // create an Axis server
    AxisServer engine = server.getAxisServer();

    // create and initialize a message context
    MessageContext msgContext = new MessageContext(engine);
    Message requestMsg = null;

    // Reusuable, buffered, content length controlled, InputStream
    NonBlockingBufferedInputStream is = new NonBlockingBufferedInputStream();

    // buffers for the headers we care about
    StringBuffer soapAction = new StringBuffer();
    StringBuffer httpRequest = new StringBuffer();
    StringBuffer fileName = new StringBuffer();
    StringBuffer cookie = new StringBuffer();
    StringBuffer cookie2 = new StringBuffer();
    StringBuffer authInfo = new StringBuffer();
    StringBuffer contentType = new StringBuffer();
    StringBuffer contentLocation = new StringBuffer();

    Message responseMsg = null;

    // prepare request (do as much as possible while waiting for the
    // next connection).  Note the next two statements are commented
    // out.  Uncomment them if you experience any problems with not
    // resetting state between requests:
    //   msgContext = new MessageContext();
    //   requestMsg = new Message("", "String");
    //msgContext.setProperty("transport", "HTTPTransport");
    msgContext.setTransportName(transportName);

    responseMsg = null;

    try {
        // assume the best
        byte[] status = OK;

        // assume we're not getting WSDL
        boolean doWsdl = false;

        // cookie for this session, if any
        String cooky = null;

        String methodName = null;

        try {
            // wipe cookies if we're doing sessions
            if (server.isSessionUsed()) {
                cookie.delete(0, cookie.length());
                cookie2.delete(0, cookie2.length());
            }
            authInfo.delete(0, authInfo.length());

            // read headers
            is.setInputStream(socket.getInputStream());
            // parse all headers into hashtable
            MimeHeaders requestHeaders = new MimeHeaders();
            int contentLength = parseHeaders(is, buf, contentType, contentLocation, soapAction, httpRequest,
                    fileName, cookie, cookie2, authInfo, requestHeaders);
            is.setContentLength(contentLength);

            int paramIdx = fileName.toString().indexOf('?');
            if (paramIdx != -1) {
                // Got params
                String params = fileName.substring(paramIdx + 1);
                fileName.setLength(paramIdx);

                log.debug(Messages.getMessage("filename00", fileName.toString()));
                log.debug(Messages.getMessage("params00", params));

                if ("wsdl".equalsIgnoreCase(params))
                    doWsdl = true;

                if (params.startsWith("method=")) {
                    methodName = params.substring(7);
                }
            }

            // Real and relative paths are the same for the
            // SimpleAxisServer
            msgContext.setProperty(Constants.MC_REALPATH, fileName.toString());
            msgContext.setProperty(Constants.MC_RELATIVE_PATH, fileName.toString());
            msgContext.setProperty(Constants.MC_JWS_CLASSDIR, "jwsClasses");
            msgContext.setProperty(Constants.MC_HOME_DIR, ".");

            // !!! Fix string concatenation
            String url = "http://" + getLocalHost() + ":" + server.getServerSocket().getLocalPort() + "/"
                    + fileName.toString();
            msgContext.setProperty(MessageContext.TRANS_URL, url);

            String filePart = fileName.toString();
            if (filePart.startsWith("axis/services/")) {
                String servicePart = filePart.substring(14);
                int separator = servicePart.indexOf('/');
                if (separator > -1) {
                    msgContext.setProperty("objectID", servicePart.substring(separator + 1));
                    servicePart = servicePart.substring(0, separator);
                }
                msgContext.setTargetService(servicePart);
            }

            if (authInfo.length() > 0) {
                // Process authentication info
                //authInfo = new StringBuffer("dXNlcjE6cGFzczE=");
                byte[] decoded = Base64.decode(authInfo.toString());
                StringBuffer userBuf = new StringBuffer();
                StringBuffer pwBuf = new StringBuffer();
                StringBuffer authBuf = userBuf;
                for (int i = 0; i < decoded.length; i++) {
                    if ((char) (decoded[i] & 0x7f) == ':') {
                        authBuf = pwBuf;
                        continue;
                    }
                    authBuf.append((char) (decoded[i] & 0x7f));
                }

                if (log.isDebugEnabled()) {
                    log.debug(Messages.getMessage("user00", userBuf.toString()));
                }

                msgContext.setUsername(userBuf.toString());
                msgContext.setPassword(pwBuf.toString());
            }

            // if get, then return simpleton document as response
            if (httpRequest.toString().equals("GET")) {

                OutputStream out = socket.getOutputStream();
                out.write(HTTP);
                if (fileName.length() == 0) {
                    out.write("301 Redirect\nLocation: /axis/\n\n".getBytes());
                    out.flush();
                    return;
                }
                out.write(status);

                if (methodName != null) {
                    String body = "<" + methodName + ">" +
                    //                               args +
                            "</" + methodName + ">";
                    String msgtxt = "<SOAP-ENV:Envelope" + " xmlns:SOAP-ENV=\"" + Constants.URI_SOAP12_ENV
                            + "\">" + "<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>";

                    ByteArrayInputStream istream = new ByteArrayInputStream(msgtxt.getBytes());
                    requestMsg = new Message(istream);
                } else if (doWsdl) {
                    engine.generateWSDL(msgContext);

                    Document doc = (Document) msgContext.getProperty("WSDL");
                    if (doc != null) {
                        XMLUtils.normalize(doc.getDocumentElement());
                        String response = XMLUtils.PrettyDocumentToString(doc);
                        byte[] respBytes = response.getBytes();

                        out.write(XML_MIME_STUFF);
                        putInt(buf, out, respBytes.length);
                        out.write(SEPARATOR);
                        out.write(respBytes);
                        out.flush();
                        return;
                    }
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append("<h2>And now... Some Services</h2>\n");
                    Iterator i = engine.getConfig().getDeployedServices();
                    sb.append("<ul>\n");
                    while (i.hasNext()) {
                        ServiceDesc sd = (ServiceDesc) i.next();
                        sb.append("<li>\n");
                        sb.append(sd.getName());
                        sb.append(" <a href=\"services/");
                        sb.append(sd.getName());
                        sb.append("?wsdl\"><i>(wsdl)</i></a></li>\n");
                        ArrayList operations = sd.getOperations();
                        if (!operations.isEmpty()) {
                            sb.append("<ul>\n");
                            for (Iterator it = operations.iterator(); it.hasNext();) {
                                OperationDesc desc = (OperationDesc) it.next();
                                sb.append("<li>" + desc.getName());
                            }
                            sb.append("</ul>\n");
                        }
                    }
                    sb.append("</ul>\n");

                    byte[] bytes = sb.toString().getBytes();

                    out.write(HTML_MIME_STUFF);
                    putInt(buf, out, bytes.length);
                    out.write(SEPARATOR);
                    out.write(bytes);
                    out.flush();
                    return;
                }
            } else {

                // this may be "" if either SOAPAction: "" or if no SOAPAction at all.
                // for now, do not complain if no SOAPAction at all
                String soapActionString = soapAction.toString();
                if (soapActionString != null) {
                    msgContext.setUseSOAPAction(true);
                    msgContext.setSOAPActionURI(soapActionString);
                }
                requestMsg = new Message(is, false, contentType.toString(), contentLocation.toString());
            }

            // Transfer HTTP headers to MIME headers for request message.
            MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
            for (Iterator i = requestHeaders.getAllHeaders(); i.hasNext();) {
                MimeHeader requestHeader = (MimeHeader) i.next();
                requestMimeHeaders.addHeader(requestHeader.getName(), requestHeader.getValue());
            }
            msgContext.setRequestMessage(requestMsg);
            // put character encoding of request to message context
            // in order to reuse it during the whole process.   
            String requestEncoding = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (requestEncoding != null) {
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, requestEncoding);
            }

            // set up session, if any
            if (server.isSessionUsed()) {
                // did we get a cookie?
                if (cookie.length() > 0) {
                    cooky = cookie.toString().trim();
                } else if (cookie2.length() > 0) {
                    cooky = cookie2.toString().trim();
                }

                // if cooky is null, cook up a cooky
                if (cooky == null) {
                    // fake one up!
                    // make it be an arbitrarily increasing number
                    // (no this is not thread safe because ++ isn't atomic)
                    int i = SimpleAxisServer.sessionIndex++;
                    cooky = "" + i;
                }

                msgContext.setSession(server.createSession(cooky));
            }

            // invoke the Axis engine
            engine.invoke(msgContext);

            // Retrieve the response from Axis
            responseMsg = msgContext.getResponseMessage();

            if (responseMsg == null) {
                status = NOCONTENT;
            }
        } catch (Exception e) {
            AxisFault af;
            if (e instanceof AxisFault) {
                af = (AxisFault) e;
                log.debug(Messages.getMessage("serverFault00"), af);
                QName faultCode = af.getFaultCode();
                if (Constants.FAULT_SOAP12_SENDER.equals(faultCode)) {
                    status = SENDER;
                } else if ("Server.Unauthorized".equals(af.getFaultCode().getLocalPart())) {
                    status = UNAUTH; // SC_UNAUTHORIZED
                } else {
                    status = ISE; // SC_INTERNAL_SERVER_ERROR
                }
            } else {
                status = ISE; // SC_INTERNAL_SERVER_ERROR
                af = AxisFault.makeFault(e);
            }

            // There may be headers we want to preserve in the
            // response message - so if it's there, just add the
            // FaultElement to it.  Otherwise, make a new one.
            responseMsg = msgContext.getResponseMessage();
            if (responseMsg == null) {
                responseMsg = new Message(af);
                responseMsg.setMessageContext(msgContext);
            } else {
                try {
                    SOAPEnvelope env = responseMsg.getSOAPEnvelope();
                    env.clearBody();
                    env.addBodyElement(new SOAPFault((AxisFault) e));
                } catch (AxisFault fault) {
                    // Should never reach here!
                }
            }
        }

        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null && responseMsg != null) {
            responseMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
        }
        // Send it on its way...
        OutputStream out = socket.getOutputStream();
        out.write(HTTP);
        out.write(status);

        if (responseMsg != null) {
            if (server.isSessionUsed() && null != cooky && 0 != cooky.trim().length()) {
                // write cookie headers, if any
                // don't sweat efficiency *too* badly
                // optimize at will
                StringBuffer cookieOut = new StringBuffer();
                cookieOut.append("\r\nSet-Cookie: ").append(cooky).append("\r\nSet-Cookie2: ").append(cooky);
                // OH, THE HUMILITY!  yes this is inefficient.
                out.write(cookieOut.toString().getBytes());
            }

            //out.write(XML_MIME_STUFF);
            out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_TYPE + ": "
                    + responseMsg.getContentType(msgContext.getSOAPConstants())).getBytes());
            // Writing the length causes the entire message to be decoded twice.
            //out.write(("\r\n" + HTTPConstants.HEADER_CONTENT_LENGTH + ": " + responseMsg.getContentLength()).getBytes());
            // putInt(out, response.length);

            // Transfer MIME headers to HTTP headers for response message.
            for (Iterator i = responseMsg.getMimeHeaders().getAllHeaders(); i.hasNext();) {
                MimeHeader responseHeader = (MimeHeader) i.next();
                out.write('\r');
                out.write('\n');
                out.write(responseHeader.getName().getBytes());
                out.write(headerEnder);
                out.write(responseHeader.getValue().getBytes());
            }

            out.write(SEPARATOR);
            responseMsg.writeTo(out);
        }

        // out.write(response);
        out.flush();
    } catch (Exception e) {
        log.info(Messages.getMessage("exception00"), e);
    } finally {
        try {
            if (socket != null)
                socket.close();
        } catch (Exception e) {
        }
    }
    if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
        // why then, quit!
        try {
            server.stop();
        } catch (Exception e) {
        }
    }

}

From source file:de.unibi.techfak.bibiserv.BiBiTools.java

/**
 * private helper method that check if teh StringBUffer end with and file
 * separator//from  ww w .j av a 2 s. c om
 *
 * @param StringBuffer to be checked
 * @return True if param end with an file separator.
 */
private boolean endWithFileSeparator(StringBuffer buf) {
    return (buf != null) && (buf.length() - separator.length() > 0)
            && (buf.substring(buf.length() - this.separator.length()).equals(this.separator));
}

From source file:org.lockss.daemon.OpenUrlResolver.java

/**
 * Return the OpenUrl query string for the specified bibliographic item.
 * /*from  w  ww  . j av a2 s . c o  m*/
 * @param bibitem the BibliographicItem
 * @return the OpenUrl query string, or null if not available
 */
static public String getOpenUrlQueryForBibliographicItem(BibliographicItem bibitem) {
    StringBuffer sb = new StringBuffer();

    String isbn = bibitem.getIsbn();
    if (!StringUtil.isNullString(isbn)) {
        sb.append("&isbn=");
        sb.append(UrlUtil.encodeQueryArg(MetadataUtil.formatIsbn(isbn)));
    }

    String issn = bibitem.getIssn();
    if (!StringUtil.isNullString(issn)) {
        sb.append("&issn=");
        sb.append(UrlUtil.encodeQueryArg(MetadataUtil.formatIssn(issn)));
    }

    String publisher = bibitem.getPublisherName();
    if (!StringUtil.isNullString(publisher)) {
        sb.append("&publisher=");
        sb.append(UrlUtil.encodeQueryArg(publisher));
    }

    String title = bibitem.getPublicationTitle();
    if (!StringUtil.isNullString(title)) {
        String pubType = bibitem.getPublicationType();
        if (!StringUtil.isNullString(pubType) && pubType.startsWith("book")) {
            sb.append("&btitle");
        } else {
            sb.append("&jtitle=");
        }
        sb.append(UrlUtil.encodeQueryArg(title));
    }

    String year = bibitem.getStartYear();
    if (!StringUtil.isNullString(year) && year.equals(bibitem.getYear())) {
        sb.append("&year=");
        sb.append(UrlUtil.encodeQueryArg(year));
    }

    String volume = bibitem.getStartVolume();
    if (!StringUtil.isNullString(volume) && volume.equals(bibitem.getVolume())) {
        sb.append("&volume=");
        sb.append(UrlUtil.encodeQueryArg(volume));
    }

    String issue = bibitem.getStartIssue();
    if (!StringUtil.isNullString(issue) && volume.equals(bibitem.getIssue())) {
        sb.append("&issue=");
        sb.append(UrlUtil.encodeQueryArg(issue));
    }

    return (sb.length() == 0) ? null : sb.substring(1);
}