List of usage examples for java.lang StringBuffer substring
@Override public synchronized String substring(int start, int end)
From source file:org.vfny.geoserver.wfs.servlets.TestWfsPost.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*ww w .j a va 2 s . com*/ * * @param request servlet request * @param response servlet response * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestString = request.getParameter("body"); String urlString = request.getParameter("url"); boolean doGet = (requestString == null) || requestString.trim().equals(""); if ((urlString == null)) { PrintWriter out = response.getWriter(); StringBuffer urlInfo = request.getRequestURL(); if (urlInfo.indexOf("?") != -1) { urlInfo.delete(urlInfo.indexOf("?"), urlInfo.length()); } String geoserverUrl = urlInfo.substring(0, urlInfo.indexOf("/", 8)) + request.getContextPath(); response.setContentType("text/html"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html>"); out.println("<head>"); out.println("<title>TestWfsPost</title>"); out.println("</head>"); out.println("<script language=\"JavaScript\">"); out.println("function doNothing() {"); out.println("}"); out.println("function sendRequest() {"); out.println(" if (checkURL()==true) {"); out.print(" document.frm.action = \""); out.print(urlInfo.toString()); out.print("\";\n"); out.println(" document.frm.target = \"_blank\";"); out.println(" document.frm.submit();"); out.println(" }"); out.println("}"); out.println("function checkURL() {"); out.println(" if (document.frm.url.value==\"\") {"); out.println(" alert(\"Please give URL before you sumbit this form!\");"); out.println(" return false;"); out.println(" } else {"); out.println(" return true;"); out.println(" }"); out.println("}"); out.println("function clearRequest() {"); out.println("document.frm.body.value = \"\";"); out.println("}"); out.println("</script>"); out.println("<body>"); out.println("<form name=\"frm\" action=\"JavaScript:doNothing()\" method=\"POST\">"); out.println("<table align=\"center\" cellspacing=\"2\" cellpadding=\"2\" border=\"0\">"); out.println("<tr>"); out.println("<td><b>URL:</b></td>"); out.print("<td><input name=\"url\" value=\""); out.print(geoserverUrl); out.print("/wfs/GetFeature\" size=\"70\" MAXLENGTH=\"100\"/></td>\n"); out.println("</tr>"); out.println("<tr>"); out.println("<td><b>Request:</b></td>"); out.println("<td><textarea cols=\"60\" rows=\"24\" name=\"body\"></textarea></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table align=\"center\">"); out.println("<tr>"); out.println("<td><input type=\"button\" value=\"Clear\" onclick=\"clearRequest()\"></td>"); out.println("<td><input type=\"button\" value=\"Submit\" onclick=\"sendRequest()\"></td>"); out.println("<td></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.close(); } else { response.setContentType("application/xml"); BufferedReader xmlIn = null; PrintWriter xmlOut = null; StringBuffer sbf = new StringBuffer(); String resp = null; try { URL u = new URL(urlString); java.net.HttpURLConnection acon = (java.net.HttpURLConnection) u.openConnection(); acon.setAllowUserInteraction(false); if (!doGet) { //System.out.println("set to post"); acon.setRequestMethod("POST"); acon.setRequestProperty("Content-Type", "application/xml"); } else { //System.out.println("set to get"); acon.setRequestMethod("GET"); } acon.setDoOutput(true); acon.setDoInput(true); acon.setUseCaches(false); //SISfixed - if there was authentication info in the request, // Pass it along the way to the target URL //DJB: applied patch in GEOS-335 String authHeader = request.getHeader("Authorization"); String username = request.getParameter("username"); if ((username != null) && !username.trim().equals("")) { String password = request.getParameter("password"); String up = username + ":" + password; byte[] encoded = Base64.encodeBase64(up.getBytes()); authHeader = "Basic " + new String(encoded); } if (authHeader != null) { acon.setRequestProperty("Authorization", authHeader); } if (!doGet) { xmlOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(acon.getOutputStream()))); xmlOut = new java.io.PrintWriter(acon.getOutputStream()); xmlOut.write(requestString); xmlOut.flush(); } // Above 400 they're all error codes, see: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html if (acon.getResponseCode() >= 400) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println("HTTP response: " + acon.getResponseCode() + "\n" + URLDecoder.decode(acon.getResponseMessage(), "UTF-8")); out.println("</servlet-exception>"); out.close(); } else { // xmlIn = new BufferedReader(new InputStreamReader( // acon.getInputStream())); // String line; // System.out.println("got encoding from acon: " // + acon.getContentType()); response.setContentType(acon.getContentType()); response.setHeader("Content-disposition", acon.getHeaderField("Content-disposition")); OutputStream output = response.getOutputStream(); int c; InputStream in = acon.getInputStream(); while ((c = in.read()) != -1) output.write(c); in.close(); output.close(); } //while ((line = xmlIn.readLine()) != null) { // out.print(line); //} } catch (Exception e) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e.toString()); out.println("</servlet-exception>"); out.close(); } finally { try { if (xmlIn != null) { xmlIn.close(); } } catch (Exception e1) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e1.toString()); out.println("</servlet-exception>"); out.close(); } try { if (xmlOut != null) { xmlOut.close(); } } catch (Exception e2) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e2.toString()); out.println("</servlet-exception>"); out.close(); } } } }
From source file:org.venice.piazza.servicecontroller.messaging.ServiceMessageWorker.java
private MediaType createMediaType(String mimeType) { MediaType mediaType;//from www .j a v a2 s . c om String type, subtype; StringBuffer sb = new StringBuffer(mimeType); int index = sb.indexOf("/"); // If a slash was found then there is a type and subtype if (index != -1) { type = sb.substring(0, index); subtype = sb.substring(index + 1, mimeType.length()); mediaType = new MediaType(type, subtype); coreLogger.log("The type is=" + type, PiazzaLogger.DEBUG); coreLogger.log("The subtype is=" + subtype, PiazzaLogger.DEBUG); } else { // Assume there is just a type for the mime, no subtype mediaType = new MediaType(mimeType); } return mediaType; }
From source file:com.ewcms.plugin.report.generate.factory.ChartFactory.java
/** * ??/* w w w. jav a 2s . co m*/ * * @param chartParam * @param sql * @return * @throws ConvertException * @throws ClassNotFoundException * @throws TypeHandlerException */ @SuppressWarnings("unchecked") private String replaceParam(Map<String, String> pageParams, Set<Parameter> paramSets, String expression, Boolean isSql) throws ConvertException, ClassNotFoundException { if (paramSets == null || paramSets.size() == 0) { return expression; } Map<String, Object> chartParam = new HashMap<String, Object>(); if (pageParams == null || pageParams.size() == 0) { for (Parameter param : paramSets) { String value = param.getDefaultValue(); if (value == null) { continue; } String className = param.getClassName(); Class<Object> forName = (Class<Object>) Class.forName(className); Object paramValue = ConvertFactory.instance.convertHandler(forName).parse(value); chartParam.put(param.getEnName(), paramValue); } } else { for (Parameter param : paramSets) { String value = pageParams.get(param.getEnName()); if (value == null) { continue; } String className = param.getClassName(); Class<Object> forName = (Class<Object>) Class.forName(className); Object paramValue = ConvertFactory.instance.convertHandler(forName).parse(value); chartParam.put(param.getEnName(), paramValue); } } int beginIndex = 0; int endIndex = 0; StringBuffer sb = new StringBuffer(expression); for (int i = 0; i < sb.length(); i++) { String p = sb.substring(i, i + 1); if (p.equals("$")) { beginIndex = i; continue; } if (p.equals("}")) { endIndex = i; } if (endIndex > beginIndex) { String temp = sb.substring(beginIndex, endIndex + 1); Iterator<Entry<String, Object>> iterator = chartParam.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> e = (Map.Entry<String, Object>) iterator.next(); if (temp.indexOf(e.getKey(), 0) != -1) { Object value = e.getValue(); if (isSql) { if (value instanceof String) { sb = sb.replace(beginIndex, endIndex + 1, "'" + value + "'"); } else if (value instanceof Date) { sb = sb.replace(beginIndex, endIndex + 1, "'" + value + "'"); } else { sb = sb.replace(beginIndex, endIndex + 1, "" + value + ""); } } else { sb = sb.replace(beginIndex, endIndex + 1, "" + value + ""); } } } beginIndex = endIndex; } } return sb.toString(); }
From source file:arena.utils.URLUtils.java
public static String addParamToURL(String baseURL, String paramName, String paramValue, String encoding, boolean replace) { StringBuffer out = new StringBuffer(); Log log = LogFactory.getLog(URLUtils.class); String useEncoding = ((encoding == null) ? "ISO-8859-1" : encoding); if ((paramName != null) && (paramValue != null)) { log.debug("URL encoding param: " + paramName + "=" + paramValue + " (ignored if null)"); String encodedParamName = encodeURLToken(paramName, useEncoding); String encodedParamValue = encodeURLToken(paramValue, useEncoding); out.append(encodedParamName).append("=").append(encodedParamValue).append("&"); // Remove if replacing int paramExistsLoc = baseURL.indexOf(encodedParamName + "="); if (replace && (paramExistsLoc != -1)) { log.debug(// w ww . j a va 2s. co m "Replacing parameter: " + paramName + " in URL: " + baseURL + " with value " + paramValue); int prevAmpersandPos = baseURL.substring(0, paramExistsLoc).lastIndexOf("&"); int nextAmpersandPos = baseURL.indexOf("&", paramExistsLoc); if (nextAmpersandPos != -1) { baseURL = baseURL.substring(0, paramExistsLoc) + baseURL.substring(nextAmpersandPos + 1); } else { baseURL = baseURL.substring(0, (prevAmpersandPos == -1) ? paramExistsLoc : prevAmpersandPos); } } } if (out.length() == 0) { return baseURL; } else if (baseURL.endsWith("?")) { return baseURL + out.substring(0, out.length() - 1); } else if (baseURL.indexOf("?") == -1) { return baseURL + "?" + out.substring(0, out.length() - 1); } else { return baseURL + "&" + out.substring(0, out.length() - 1); } }
From source file:org.latticesoft.util.common.StringUtil.java
/** * Formats a list into string/*from w w w . j av a 2s .c o m*/ * @param l the list to be formatted * @param separator the separator between the elements * @param enclosing to include the enclosing sq brackets or not * @return the formatted string */ public static String formatList(List l, String separator, boolean enclosing) { if (l == null || separator == null) { return null; } StringBuffer sb = new StringBuffer(); if (enclosing) { sb.append("["); } for (int i = 0; i < l.size(); i++) { Object o = l.get(i); if (o != null) { sb.append(o).append(separator); } } int len = separator.length(); if (sb.length() > len) { int startIndex = sb.length() - len; int endIndex = sb.length(); String s = sb.substring(startIndex, endIndex); if (s.equals(separator)) { for (int i = 0; i < len; i++) { sb.deleteCharAt(sb.length() - 1); } } } if (enclosing) { sb.append("]"); } return sb.toString(); }
From source file:com.all.backend.web.controller.LoginServerController.java
private String getEnvironment(StringBuffer requestURL) { String environment = javaMailProperties.getProperty(ENVIRONMENT); log.debug("ENVIRONMENT : " + environment); String url = ""; if (environment.equals("production")) { url = ALL_BACKEND_CONFIRM_URL + "?registrationPendingId="; } else {/*from w ww . j a v a 2 s . c o m*/ url = requestURL.substring(0, requestURL.lastIndexOf("/") + 1) + "registration/confirmRegistration?registrationPendingId="; } log.debug("URL de la liga de confirmacion < " + url + ">"); return url; }
From source file:com.tasktop.internal.hp.qc.core.model.comments.mylyn3_8.HtmlStreamTokenizer_m3_8.java
/** * Replaces (in-place) HTML escapes in a StringBuffer with their corresponding characters. * //from w ww .j ava 2 s . c o m * @deprecated use {@link StringEscapeUtils#unescapeHtml(String)} instead */ @Deprecated public static StringBuffer unescape(StringBuffer sb) { int i = 0; // index into the unprocessed section of the buffer int j = 0; // index into the processed section of the buffer while (i < sb.length()) { char ch = sb.charAt(i); if (ch == '&') { int start = i; String escape = null; for (i = i + 1; i < sb.length(); i++) { ch = sb.charAt(i); if (!Character.isLetterOrDigit(ch) && !(ch == '#' && i == (start + 1))) { escape = sb.substring(start + 1, i); break; } } if (i == sb.length() && i != (start + 1)) { escape = sb.substring(start + 1); } if (escape != null) { Character character = parseReference(escape); if (character != null && !((0x0A == character || 0x0D == character || 0x09 == ch) || (character >= 0x20 && character <= 0xD7FF) || (character >= 0xE000 && character <= 0xFFFD) || (character >= 0x10000 && character <= 0x10FFFF))) { // Character is an invalid xml character // http://www.w3.org/TR/REC-xml/#charsets character = null; } if (character != null) { ch = character.charValue(); } else { // not an HTML escape; rewind i = start; ch = '&'; } } } sb.setCharAt(j, ch); i++; j++; } sb.setLength(j); return sb; }
From source file:org.apache.fop.render.ps.PSPainter.java
private int writePostScriptString(StringBuffer buffer, StringBuffer string, boolean multiByte, int lineStart) { buffer.append(multiByte ? '<' : '('); int l = string.length(); int index = 0; int maxCol = 200; buffer.append(string.substring(index, Math.min(index + maxCol, l))); index += maxCol;//ww w.j a va 2s . co m while (index < l) { if (!multiByte) { buffer.append('\\'); } buffer.append(PSGenerator.LF); lineStart = buffer.length(); buffer.append(string.substring(index, Math.min(index + maxCol, l))); index += maxCol; } buffer.append(multiByte ? '>' : ')'); return lineStart; }
From source file:org.apache.hadoop.mapred.TaskMemoryManagerThread.java
@Override public void run() { LOG.info("Starting thread: " + this.getClass()); while (true) { // Print the processTrees for debugging. if (LOG.isDebugEnabled()) { StringBuffer tmp = new StringBuffer("[ "); for (ProcessTreeInfo p : processTreeInfoMap.values()) { tmp.append(p.getPID());//from ww w .java 2 s .c o m tmp.append(" "); } LOG.debug("Current ProcessTree list : " + tmp.substring(0, tmp.length()) + "]"); } //Add new Tasks synchronized (tasksToBeAdded) { processTreeInfoMap.putAll(tasksToBeAdded); tasksToBeAdded.clear(); } //Remove finished Tasks synchronized (tasksToBeRemoved) { for (TaskAttemptID tid : tasksToBeRemoved) { processTreeInfoMap.remove(tid); } tasksToBeRemoved.clear(); } long memoryStillInUsage = 0; // Now, check memory usage and kill any overflowing tasks for (Iterator<Map.Entry<TaskAttemptID, ProcessTreeInfo>> it = processTreeInfoMap.entrySet() .iterator(); it.hasNext();) { Map.Entry<TaskAttemptID, ProcessTreeInfo> entry = it.next(); TaskAttemptID tid = entry.getKey(); ProcessTreeInfo ptInfo = entry.getValue(); try { String pId = ptInfo.getPID(); // Initialize any uninitialized processTrees if (pId == null) { // get pid from taskAttemptId pId = taskTracker.getPid(ptInfo.getTID()); if (pId != null) { // PID will be null, either if the pid file is yet to be created // or if the tip is finished and we removed pidFile, but the TIP // itself is still retained in runningTasks till successful // transmission to JT ProcfsBasedProcessTree pt = new ProcfsBasedProcessTree(pId, ProcessTree.isSetsidAvailable); LOG.debug("Tracking ProcessTree " + pId + " for the first time"); ptInfo.setPid(pId); ptInfo.setProcessTree(pt); } } // End of initializing any uninitialized processTrees if (pId == null) { continue; // processTree cannot be tracked } LOG.debug("Constructing ProcessTree for : PID = " + pId + " TID = " + tid); ProcfsBasedProcessTree pTree = ptInfo.getProcessTree(); pTree = pTree.getProcessTree(); // get the updated process-tree ptInfo.setProcessTree(pTree); // update ptInfo with proces-tree of // updated state long currentMemUsage = pTree.getCumulativeVmem(); // as processes begin with an age 1, we want to see if there // are processes more than 1 iteration old. long curMemUsageOfAgedProcesses = pTree.getCumulativeVmem(1); long limit = ptInfo.getMemLimit(); LOG.info(String.format(MEMORY_USAGE_STRING, pId, tid.toString(), currentMemUsage, limit)); if (isProcessTreeOverLimit(tid.toString(), currentMemUsage, curMemUsageOfAgedProcesses, limit)) { // Task (the root process) is still alive and overflowing memory. // Dump the process-tree and then clean it up. String msg = "TaskTree [pid=" + pId + ",tipID=" + tid + "] is running beyond memory-limits. Current usage : " + currentMemUsage + "bytes. Limit : " + limit + "bytes. Killing task. \nDump of the process-tree for " + tid + " : \n" + pTree.getProcessTreeDump(); LOG.warn(msg); // kill the task TaskInProgress tip = taskTracker.runningTasks.get(tid); if (tip != null) { String[] diag = msg.split("\n"); tip.getStatus().setDiagnosticInfo(diag[0]); } taskTracker.cleanUpOverMemoryTask(tid, true, msg); it.remove(); LOG.info("Removed ProcessTree with root " + pId); } else { // Accounting the total memory in usage for all tasks that are still // alive and within limits. memoryStillInUsage += currentMemUsage; } } catch (Exception e) { // Log the exception and proceed to the next task. LOG.warn("Uncaught exception in TaskMemoryManager " + "while managing memory of " + tid + " : " + StringUtils.stringifyException(e)); } } if (memoryStillInUsage > maxMemoryAllowedForAllTasks) { LOG.warn("The total memory in usage " + memoryStillInUsage + " is still overflowing TTs limits " + maxMemoryAllowedForAllTasks + ". Trying to kill a few tasks with the least progress."); killTasksWithLeastProgress(memoryStillInUsage); } // Sleep for some time before beginning next cycle try { LOG.debug(this.getClass() + " : Sleeping for " + monitoringInterval + " ms"); Thread.sleep(monitoringInterval); } catch (InterruptedException ie) { LOG.warn(this.getClass() + " interrupted. Finishing the thread and returning."); return; } } }
From source file:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java
@Override public void transmit(SLResult slResult) throws IOException { log.trace("Sending data."); if (urlEncoded) { ///*from w w w.ja va 2 s. c o m*/ // application/x-www-form-urlencoded (legacy, SL < 1.2) // OutputStream os = connection.getOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET); // ResponseType streamWriter.write(FORMPARAM_RESPONSETYPE); streamWriter.write("="); streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8")); streamWriter.write("&"); // XMLResponse / Binary Response if (slResult.getResultType() == SLResultType.XML) { streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE); } else { streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE); } streamWriter.write("="); streamWriter.flush(); URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter); slResult.writeTo(new StreamResult(urlEnc), false); urlEnc.flush(); // transfer parameters char[] cbuf = new char[512]; int len; for (HTTPFormParameter formParameter : httpFormParameter) { streamWriter.write("&"); streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8")); streamWriter.write("="); InputStreamReader reader = new InputStreamReader(formParameter.getData(), (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was // application/x-www-form-urlencoded, // formParam therefore UTF-8 while ((len = reader.read(cbuf)) != -1) { urlEnc.write(cbuf, 0, len); } urlEnc.flush(); } streamWriter.close(); } else { // // multipart/form-data (conforming to SL 1.2) // ArrayList<Part> parts = new ArrayList<Part>(); // ResponseType StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8"); responseType.setTransferEncoding(null); parts.add(responseType); // XMLResponse / Binary Response SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING); if (slResult.getResultType() == SLResultType.XML) { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); slResultPart.setCharSet(XML_RESPONSE_ENCODING); } else { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); } parts.add(slResultPart); // transfer parameters for (HTTPFormParameter formParameter : httpFormParameter) { InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData()); FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(), formParameter.getCharSet()); part.setTransferEncoding(formParameter.getTransferEncoding()); parts.add(part); } OutputStream os = connection.getOutputStream(); Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes()); os.close(); } // MultipartRequestEntity PostMethod InputStream is = null; try { is = connection.getInputStream(); } catch (IOException iox) { log.info("Failed to get InputStream of HTTPUrlConnection.", iox); } log.trace("Reading response."); response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is); Map<String, String> responseHttpHeaders = new HashMap<String, String>(); Map<String, List<String>> httpHeaders = connection.getHeaderFields(); for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) { String key = keyIt.next(); StringBuffer value = new StringBuffer(); for (String val : httpHeaders.get(key)) { value.append(val); value.append(HttpUtil.SEPARATOR[0]); } String valString = value.substring(0, value.length() - 1); if ((key != null) && (value.length() > 0)) { responseHttpHeaders.put(key, valString); } } response.setResponseHttpHeaders(responseHttpHeaders); }