List of usage examples for java.lang StringBuilder subSequence
CharSequence subSequence(int start, int end);
From source file:com.vuze.android.remote.rpc.RestJsonClient.java
public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers, UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException { long readTime = 0; long connSetupTime = 0; long connTime = 0; int bytesRead = 0; if (DEBUG_DETAILED) { Log.d(TAG, id + "] Execute " + url); }// ww w. j ava 2 s . c o m long now = System.currentTimeMillis(); long then; Map<?, ?> json = Collections.EMPTY_MAP; try { URI uri = new URI(url); int port = uri.getPort(); BasicHttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote"); DefaultHttpClient httpclient; if ("https".equals(uri.getScheme())) { httpclient = MySSLSocketFactory.getNewHttpClient(port); } else { httpclient = new DefaultHttpClient(basicHttpParams); } //AndroidHttpClient.newInstance("Vuze Android Remote"); // This doesn't set the "Authorization" header!? httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds); // Prepare a request object HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException if (creds != null) { byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes(); String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length); httpRequest.setHeader("Authorization", "Basic " + encoding); } if (jsonPost != null) { HttpPost post = (HttpPost) httpRequest; String postString = JSONUtils.encodeToJSON(jsonPost); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "] Post: " + postString); } AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getCompressedEntity(postString) : new StringEntity(postString); post.setEntity(entity); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { setupRequestFroyo(httpRequest); } if (headers != null) { for (Header header : headers) { httpRequest.setHeader(header); } } // Execute the request HttpResponse response; then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connSetupTime = (then - now); now = then; } httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) { if (i < 2) { return true; } return false; } }); response = httpclient.execute(httpRequest); then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connTime = (then - now); now = then; } HttpEntity entity = response.getEntity(); // XXX STATUSCODE! StatusLine statusLine = response.getStatusLine(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "StatusCode: " + statusLine.getStatusCode()); } if (entity != null) { long contentLength = entity.getContentLength(); if (contentLength >= Integer.MAX_VALUE - 2) { throw new RPCException("JSON response too large"); } // A Simple JSON Response Read InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getUngzippedContent(entity) : entity.getContent(); InputStreamReader isr = new InputStreamReader(instream, "utf8"); StringBuilder sb = null; BufferedReader br = null; // JSONReader is 10x slower, plus I get more OOM errors.. :( // final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false // : DEFAULT_USE_STRINGBUFFER; final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER; if (useStringBuffer) { // Setting capacity saves StringBuffer from going through many // enlargeBuffers, and hopefully allows toString to not make a copy sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512); } else { if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "Using BR. ContentLength = " + contentLength); } br = new BufferedReader(isr, 8192); br.mark(32767); } try { // 9775 files on Nexus 7 (~2,258,731 bytes) // fastjson 1.1.46 (String) : 527- 624ms // fastjson 1.1.39 (String) : 924-1054ms // fastjson 1.1.39 (StringBuilder): 1227-1463ms // fastjson 1.1.39 (BR) : 2233-2260ms // fastjson 1.1.39 (isr) : 2312ms // GSON 2.2.4 (String) : 1539-1760ms // GSON 2.2.4 (BufferedReader) : 2646-3060ms // JSON-SMART 1.3.1 (String) : 572- 744ms (OOMs more often than fastjson) if (useStringBuffer) { char c[] = new char[8192]; while (true) { int read = isr.read(c); if (read < 0) { break; } sb.append(c, 0, read); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); if (DEBUG_DETAILED) { if (sb.length() > 2000) { Log.d(TAG, id + "] " + sb.substring(0, 2000) + "..."); } else { Log.d(TAG, id + "] " + sb.toString()); } } bytesRead = sb.length(); readTime = (then - now); now = then; } json = JSONUtils.decodeJSON(sb.toString()); //json = JSONUtilsGSON.decodeJSON(sb.toString()); } else { //json = JSONUtils.decodeJSON(isr); json = JSONUtils.decodeJSON(br); //json = JSONUtilsGSON.decodeJSON(br); } } catch (Exception pe) { // StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 409) { throw new RPCException(response, "409"); } try { String line; if (useStringBuffer) { line = sb.subSequence(0, Math.min(128, sb.length())).toString(); } else { br.reset(); line = br.readLine().trim(); } isr.close(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "]line: " + line); } Header contentType = entity.getContentType(); if (line.startsWith("<") || line.contains("<html") || (contentType != null && contentType.getValue().startsWith("text/html"))) { // TODO: use android strings.xml throw new RPCException(response, "Could not retrieve remote client location information. The most common cause is being on a guest wifi that requires login before using the internet."); } } catch (IOException ignore) { } Log.e(TAG, id, pe); if (statusLine != null) { String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n" + pe.getMessage(); throw new RPCException(msg, pe); } throw new RPCException(pe); } finally { closeOnNewThread(useStringBuffer ? isr : br); } if (AndroidUtils.DEBUG_RPC) { // Log.d(TAG, id + "]JSON Result: " + json); } } } catch (RPCException e) { throw e; } catch (Throwable e) { Log.e(TAG, id, e); throw new RPCException(e); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime + "ms, parsed in " + (then - now) + "ms"); } return json; }
From source file:com.arksoft.epamms.ZGlobal1_Operation.java
public int InsertOI_DataIntoTemplateFile(View ViewToWindow, View vResultSet, String stringOutputFileName, String stringTemplateFileName, String stringAltFileName, String stringRootEntityName) throws IOException { int hFileTo;//ww w .j a v a 2s . c o m @SuppressWarnings("unused") String stringMemory; String stringMemoryNew = null; @SuppressWarnings("unused") String stringMemoryStartNew; StringBuilder sbMemoryStartOld = new StringBuilder(); @SuppressWarnings("unused") String stringMemoryEndOld; String stringMemoryStartArea = null; String stringMemoryEndArea = null; long selMemory = 0; int selMemoryNew; int lTemplateLth; int lSelectedCount; int lCurrentCount; int lTotalOutputSize; @SuppressWarnings("unused") int lLthNew; int nRC; // The size of the new memory will try to allow for the number of select // copies to be made of the input template. It will thus add 50000 bytes // of variable data to the template size and multiply that by the number // of items selected. lSelectedCount = 0; nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) lSelectedCount++; nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } // We'll just exit here if nothing was selected. if (lSelectedCount == 0) return 0; lTemplateLth = ReadFileDataIntoMemory(vResultSet, stringTemplateFileName, selMemory, sbMemoryStartOld); // Exit if the template file is empty or if there is an error opening it. if (lTemplateLth <= 0) { IssueError(vResultSet, 0, 0, "Can't open Template file."); return 0; } lTotalOutputSize = (lTemplateLth + 50000) * lSelectedCount; //? selMemoryNew = SysAllocMemory( stringMemoryNew, lTotalOutputSize, 0, zCOREMEM_ALLOC, 0 ); // DrAllocTaskMemory( (zCOREMEM) &stringMemoryNew, lTotalOutputSize ); // TraceLine( "InsertOI_DataIntoTemplateFile: 0x%x Size: %d", // (int) stringMemoryNew, lTotalOutputSize ); stringMemoryEndOld = sbMemoryStartOld.subSequence(lTemplateLth, -1).toString(); // Initialize Output values. stringMemoryStartNew = stringMemoryNew; lLthNew = 0; // Copy the first brace that starts the file. // stringMemory = cbMemoryStartOld.toString( ); TODO This is all wrong ... recode correctly in Java when needed // stringMemoryNew = stringMemory; // stringMemory++; // stringMemoryNew++; // Set the start of repeatable area (one per document copy) as second character in // Template file. // stringMemoryStartArea = stringMemory; // Set the end of repeatable area as one character before the last character in Template file. // stringMemoryEndArea = stringMemoryEndOld - 1; // For each selected item, map the repeatable data in the template to the output buffer. nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); lCurrentCount = 0; while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) { // If this is any page but the first, add in the page break // characters. lCurrentCount++; if (lCurrentCount > 1) { // TODO what's the problem with this line??? zstrcpy( stringMemoryNew, "\x0D\x0A\\par \\page \\hich\\af0\\dbch\\af28\\loch\\f0 " ); stringMemoryNew = stringMemoryNew + 41; } stringMemory = stringMemoryStartArea; // Perform the normal mapping code here. //? nRC = CopyWithInsertMemoryArea( vResultSet, stringMemoryStartArea, stringMemoryEndArea, //? stringMemoryNew, "", stringMemoryNew, lTotalOutputSize, "", // no embedded images //? 1 ); // Text if (nRC < 0) return nRC; } nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } // Finally copy the closing brace to the output file. // stringMemoryNew = stringMemoryEndArea; TODO This is all wrong ... recode correctly in Java when needed // stringMemory++; // stringMemoryNew++; // lLthNew = (int) (stringMemoryNew - stringMemoryStartNew); //? SysFreeMemory( selMemory ); // DrFreeTaskMemory( stringMemoryStartOld ); hFileTo = m_KZOEP1AA.SysOpenFile(ViewToWindow, stringOutputFileName, COREFILE_WRITE); if (hFileTo < 0) { //? SysFreeMemory( selMemoryNew ); // DrFreeTaskMemory( stringMemoryNew ); IssueError(vResultSet, 0, 0, "Write Open Error"); return -1; } // WriteFile( hFileTo, stringMemoryStartNew, lLthNew, ulRC, 0 ); TODO This is all wrong ... recode correctly in Java when needed m_KZOEP1AA.SysCloseFile(ViewToWindow, hFileTo, 0); //? SysFreeMemory( selMemoryNew ); // DrFreeTaskMemory( stringMemoryNew ); return 0; }
From source file:com.quinsoft.noa.ZGLOBAL1_Operation.java
public int InsertOI_DataIntoTemplateFile(View ViewToWindow, View vResultSet, String stringOutputFileName, String stringTemplateFileName, String stringAltFileName, String stringRootEntityName) throws IOException { int hFileTo;//from ww w.j a v a 2 s . co m @SuppressWarnings("unused") String stringMemory; String stringMemoryNew = null; @SuppressWarnings("unused") String stringMemoryStartNew; StringBuilder sbMemoryStartOld = new StringBuilder(); @SuppressWarnings("unused") String stringMemoryEndOld; String stringMemoryStartArea = null; String stringMemoryEndArea = null; long selMemory = 0; int selMemoryNew; int lTemplateLth; int lSelectedCount; int lCurrentCount; int lTotalOutputSize; @SuppressWarnings("unused") int lLthNew; int nRC; // The size of the new memory will try to allow for the number of select // copies to be made of the input template. It will thus add 50000 bytes // of variable data to the template size and multiply that by the number // of items selected. lSelectedCount = 0; nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) lSelectedCount++; nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } // We'll just exit here if nothing was selected. if (lSelectedCount == 0) return 0; lTemplateLth = ReadFileDataIntoMemory(vResultSet, stringTemplateFileName, selMemory, sbMemoryStartOld); // Exit if the template file is empty or if there is an error opening it. if (lTemplateLth <= 0) { IssueError(vResultSet, 0, 0, "Can't open Template file."); return 0; } lTotalOutputSize = (lTemplateLth + 50000) * lSelectedCount; //? selMemoryNew = SysAllocMemory( stringMemoryNew, lTotalOutputSize, 0, zCOREMEM_ALLOC, 0 ); // DrAllocTaskMemory( (zCOREMEM) &stringMemoryNew, lTotalOutputSize ); // TraceLine( "InsertOI_DataIntoTemplateFile: 0x%x Size: %d", // (int) stringMemoryNew, lTotalOutputSize ); stringMemoryEndOld = sbMemoryStartOld.subSequence(lTemplateLth, -1).toString(); // Initialize Output values. stringMemoryStartNew = stringMemoryNew; lLthNew = 0; // Copy the first brace that starts the file. // stringMemory = cbMemoryStartOld.toString( ); TODO This is all wrong ... recode correctly in Java when needed // stringMemoryNew = stringMemory; // stringMemory++; // stringMemoryNew++; // Set the start of repeatable area (one per document copy) as second character in // Template file. // stringMemoryStartArea = stringMemory; // Set the end of repeatable area as one character before the last character in Template file. // stringMemoryEndArea = stringMemoryEndOld - 1; // For each selected item, map the repeatable data in the template to the output buffer. nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); lCurrentCount = 0; while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) { // If this is any page but the first, add in the page break // characters. lCurrentCount++; if (lCurrentCount > 1) { // TODO what's the problem with this line??? zstrcpy( stringMemoryNew, "\x0D\x0A\\par \\page \\hich\\af0\\dbch\\af28\\loch\\f0 " ); stringMemoryNew = stringMemoryNew + 41; } stringMemory = stringMemoryStartArea; // Perform the normal mapping code here. //? nRC = CopyWithInsertMemoryArea( vResultSet, stringMemoryStartArea, stringMemoryEndArea, //? stringMemoryNew, "", stringMemoryNew, lTotalOutputSize, "", // no embedded images //? 1 ); // Text if (nRC < 0) return nRC; } nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } // Finally copy the closing brace to the output file. // stringMemoryNew = stringMemoryEndArea; TODO This is all wrong ... recode correctly in Java when needed // stringMemory++; // stringMemoryNew++; // lLthNew = (int) (stringMemoryNew - stringMemoryStartNew); //? SysFreeMemory( selMemory ); // DrFreeTaskMemory( stringMemoryStartOld ); hFileTo = m_KZOEP1AA.SysOpenFile(ViewToWindow, stringOutputFileName, COREFILE_WRITE); if (hFileTo < 0) { //? SysFreeMemory( selMemoryNew ); // DrFreeTaskMemory( stringMemoryNew ); IssueError(vResultSet, 0, 0, "Write Open Error"); return -1; } // WriteFile( hFileTo, stringMemoryStartNew, lLthNew, ulRC, 0 ); TODO This is all wrong ... recode correctly in Java when needed m_KZOEP1AA.SysCloseFile(ViewToWindow, hFileTo, 0); //? SysFreeMemory( selMemoryNew ); // DrFreeTaskMemory( stringMemoryNew ); return 0; }
From source file:com.quinsoft.epamms.ZGlobal1_Operation.java
public int InsertOI_DataIntoTemplateFileOld(View ViewToWindow, View vResultSet, String stringOutputFileName, String stringTemplateFileName, String stringAltFileName, String stringRootEntityName) throws IOException { int hFileTo;/*from www . j a va 2s.c o m*/ @SuppressWarnings("unused") String stringMemory; String stringMemoryNew = null; @SuppressWarnings("unused") String stringMemoryStartNew; StringBuilder sbMemoryStartOld = new StringBuilder(); @SuppressWarnings("unused") String stringMemoryEndOld; String stringMemoryStartArea = null; String stringMemoryEndArea = null; long selMemory = 0; int selMemoryNew; int lTemplateLth; int lSelectedCount; int lCurrentCount; int lTotalOutputSize; @SuppressWarnings("unused") int lLthNew; int nRC; // The size of the new memory will try to allow for the number of select // copies to be made of the input template. It will thus add 50000 bytes // of variable data to the template size and multiply that by the number // of items selected. lSelectedCount = 0; nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) lSelectedCount++; nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } // We'll just exit here if nothing was selected. if (lSelectedCount == 0) return 0; lTemplateLth = ReadFileDataIntoMemory(vResultSet, stringTemplateFileName, selMemory, sbMemoryStartOld); // Exit if the template file is empty or if there is an error opening it. if (lTemplateLth <= 0) { IssueError(vResultSet, 0, 0, "Can't open Template file."); return 0; } lTotalOutputSize = (lTemplateLth + 50000) * lSelectedCount; //? selMemoryNew = SysAllocMemory( stringMemoryNew, lTotalOutputSize, 0, zCOREMEM_ALLOC, 0 ); // DrAllocTaskMemory( (zCOREMEM) &stringMemoryNew, lTotalOutputSize ); // TraceLine( "InsertOI_DataIntoTemplateFile: 0x%x Size: %d", // (int) stringMemoryNew, lTotalOutputSize ); stringMemoryEndOld = sbMemoryStartOld.subSequence(lTemplateLth, -1).toString(); // Initialize Output values. stringMemoryStartNew = stringMemoryNew; lLthNew = 0; // Copy the first brace that starts the file. // stringMemory = cbMemoryStartOld.toString( ); TODO This is all wrong ... recode correctly in Java when needed // stringMemoryNew = stringMemory; // stringMemory++; // stringMemoryNew++; // Set the start of repeatable area (one per document copy) as second character in // Template file. // stringMemoryStartArea = stringMemory; // Set the end of repeatable area as one character before the last character in Template file. // stringMemoryEndArea = stringMemoryEndOld - 1; // For each selected item, map the repeatable data in the template to the output buffer. nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); lCurrentCount = 0; while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) { // If this is any page but the first, add in the page break // characters. lCurrentCount++; if (lCurrentCount > 1) { // TODO what's the problem with this line??? zstrcpy( stringMemoryNew, "\x0D\x0A\\par \\page \\hich\\af0\\dbch\\af28\\loch\\f0 " ); stringMemoryNew = stringMemoryNew + 41; } stringMemory = stringMemoryStartArea; // Perform the normal mapping code here. //? nRC = CopyWithInsertMemoryArea( vResultSet, stringMemoryStartArea, stringMemoryEndArea, //? stringMemoryNew, "", stringMemoryNew, lTotalOutputSize, "", // no embedded images //? 1 ); // Text if (nRC < 0) return nRC; } nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } // Finally copy the closing brace to the output file. // stringMemoryNew = stringMemoryEndArea; TODO This is all wrong ... recode correctly in Java when needed // stringMemory++; // stringMemoryNew++; // lLthNew = (int) (stringMemoryNew - stringMemoryStartNew); //? SysFreeMemory( selMemory ); // DrFreeTaskMemory( stringMemoryStartOld ); hFileTo = m_KZOEP1AA.SysOpenFile(ViewToWindow, stringOutputFileName, COREFILE_WRITE); if (hFileTo < 0) { //? SysFreeMemory( selMemoryNew ); // DrFreeTaskMemory( stringMemoryNew ); IssueError(vResultSet, 0, 0, "Write Open Error"); return -1; } // WriteFile( hFileTo, stringMemoryStartNew, lLthNew, ulRC, 0 ); TODO This is all wrong ... recode correctly in Java when needed m_KZOEP1AA.SysCloseFile(ViewToWindow, hFileTo, 0); //? SysFreeMemory( selMemoryNew ); // DrFreeTaskMemory( stringMemoryNew ); return 0; }
From source file:com.arksoft.epamms.ZGlobal1_Operation.java
public int InsertOI_DataIntoEmailTemplate(View ViewToWindow, View vResultSet, String stringSMTPServer, String stringEMailUserName, String stringEMailPassword, String stringSenderEMailAddress, String stringSubjectLine, String stringAttachmentFileName, String stringTemplateFileName, String stringAltFileName, String stringRootEntityName, int lFlags) throws IOException { String stringEmbeddedImages; // should be WAY more than enough String stringRecipientEMailAddress = null; int nHasAttachment; int nMimeType; int lConnection; // int hFileTo; @SuppressWarnings("unused") String stringMemory;/* w ww .ja v a 2 s . co m*/ String stringMemoryNew; String stringMemoryNewHold = null; String stringMemoryStartEmailBody; StringBuilder sbMemoryStartOld = new StringBuilder(256); @SuppressWarnings("unused") String stringMemoryEndOld; String stringMemoryStartArea = null; String stringMemoryEndArea = null; long selMemory = 0; long selMemoryNew; int lTemplateLth; String stringAltMemory; String stringAltMemoryNew; String stringAltMemoryNewHold = null; @SuppressWarnings("unused") String stringAltMemoryStartEmailBody; StringBuilder sbAltMemoryStartOld = new StringBuilder(256); @SuppressWarnings("unused") String stringAltMemoryEndOld; String stringAltMemoryStartArea = null; String stringAltMemoryEndArea = null; long selAltMemory = 0; long selAltMemoryNew = 0; long lAltTemplateLth; long lAltTotalOutputSize = 0; @SuppressWarnings("unused") int lAltLthNew; int lSelectedCount; int lCurrentCount; int lTotalOutputSize; @SuppressWarnings("unused") int lLthNew; boolean bNoEmailAddress = false; // zULONG ulRC; int nRC; if ((lFlags & 0x00000001) != 0) nHasAttachment = 1; // has attachment else nHasAttachment = 0; // no attachment if ((lFlags & 0x00000002) != 0) nMimeType = 2; // HTML else nMimeType = 1; // Text // The size of the new memory will add 8000 bytes of variable data to the // template size. lSelectedCount = 0; nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) { stringRecipientEMailAddress = GetStringFromAttribute(stringRecipientEMailAddress, vResultSet, "Person", "eMailAddress"); if (stringRecipientEMailAddress.isEmpty() == false) lSelectedCount++; else { String lastName = null; String firstName = null; String middleName = null; if (bNoEmailAddress == false) { bNoEmailAddress = true; TraceLineS("EMail NOT sent Subject: ", stringSubjectLine); } lastName = GetStringFromAttribute(lastName, vResultSet, "Person", "LastName"); firstName = GetStringFromAttribute(firstName, vResultSet, "Person", "FirstName"); middleName = GetStringFromAttribute(middleName, vResultSet, "Person", "MiddleName"); stringRecipientEMailAddress = lastName + ", " + firstName + " " + middleName; TraceLineS(" No EMail address for: ", stringRecipientEMailAddress); } } nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } if (bNoEmailAddress && (lFlags & 0x00000010) != 0) { if (OperatorPrompt(vResultSet, "EMail not sent to recipient(s)", "See Zeidon Trace for list ... Continue?", TRUE, zBUTTONS_YESNO, zRESPONSE_NO, 0) == zRESPONSE_NO) { return 0; } } // We'll just exit here if nothing was selected. if (lSelectedCount == 0) return 0; lTemplateLth = ReadFileDataIntoMemory(vResultSet, stringTemplateFileName, selMemory, sbMemoryStartOld); // Exit if the template file is empty or if there is an error opening it. if (lTemplateLth <= 0) { IssueError(vResultSet, 0, 0, "Can't open Template file."); return 0; } lAltTemplateLth = 0; if (nMimeType == 2) // HTML { if (stringAltFileName != null && stringAltFileName.isEmpty() == false) { //? lAltTemplateLth = ReadFileDataIntoMemory( vResultSet, stringAltFileName, selAltMemory, sbAltMemoryStartOld ); } // Exit if the alt template file is empty or if there is an error opening it. if (lAltTemplateLth > 0) { lAltTotalOutputSize = lAltTemplateLth + 8000; //? selAltMemoryNew = SysAllocMemory( stringAltMemoryNewHold, lAltTotalOutputSize, 0, zCOREMEM_ALLOC, 0 ); } else { // IssueError( vResultSet, 0, 0, "Can't open Alt Template file." ); // return 0; } } lTotalOutputSize = lTemplateLth + 8000; //? selMemoryNew = SysAllocMemory( stringMemoryNewHold, lTotalOutputSize, 0, zCOREMEM_ALLOC, 0 ); // DrAllocTaskMemory( (zCOREMEM) &stringMemoryNewHold, lTotalOutputSize ); // TraceLine( "InsertOI_DataIntoEmailTemplate: 0x%x Size: %d", // (int) stringMemoryNewHold, lTotalOutputSize ); lConnection = m_ZDRVROPR.CreateSeeConnection(stringSMTPServer, stringSenderEMailAddress, stringEMailUserName, stringEMailPassword); // For each selected item, map the repeatable data in the template to the output buffer. lCurrentCount = 0; nRC = SetCursorFirstEntity(vResultSet, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { nRC = GetSelectStateOfEntity(vResultSet, stringRootEntityName); if (nRC == 1) { GetStringFromAttribute(stringRecipientEMailAddress, vResultSet, "Person", "eMailAddress"); if (stringRecipientEMailAddress.isEmpty() == false) { if (lAltTemplateLth > 0) { stringAltMemoryNew = stringAltMemoryNewHold; lCurrentCount++; stringAltMemoryEndOld = sbAltMemoryStartOld.subSequence(lTemplateLth, -1).toString(); // Initialize Output values. stringAltMemoryStartEmailBody = stringAltMemoryNew; lAltLthNew = 0; // Copy the first brace that starts the file. // stringAltMemory = cbAltMemoryStartOld.toString( ); TODO This is all wrong ... recode correctly in Java when needed // stringAltMemoryNew = stringAltMemory; // stringAltMemory++; // stringAltMemoryNew++; // Set the start of repeatable area (one per document copy) as // second character in Template file. // stringAltMemoryStartArea = stringAltMemory; // Set the end of repeatable area as one character before the last // character in Template file. // stringAltMemoryEndArea = stringAltMemoryEndOld - 1; stringAltMemory = stringAltMemoryStartArea; // Perform the normal mapping code here. //? nRC = CopyWithInsertMemoryArea( vResultSet, stringAltMemoryStartArea, stringAltMemoryEndArea, //? stringAltMemoryNew, "", stringAltMemoryNewHold, //? lAltTotalOutputSize, "", 1 ); if (nRC < 0) return nRC; // Finally copy the closing brace to the output file. stringAltMemoryNew = stringAltMemoryEndArea; // stringAltMemory++; TODO This is all wrong ... recode correctly in Java when needed // stringAltMemoryNew++; // lAltLthNew = (int) (stringAltMemoryNew - stringAltMemoryStartEmailBody); } else stringAltMemory = ""; stringMemoryNew = stringMemoryNewHold; lCurrentCount++; // stringMemoryEndOld = cbMemoryStartOld + lTemplateLth; TODO This is all wrong ... recode correctly in Java when needed // Initialize Output values. stringMemoryStartEmailBody = stringMemoryNew; lLthNew = 0; // Copy the first brace that starts the file. // stringMemory = cbMemoryStartOld; TODO This is all wrong ... recode correctly in Java when needed // stringMemoryNew = stringMemory; // stringMemory++; // stringMemoryNew++; // Set the start of repeatable area (one per document copy) as // second character in Template file. // stringMemoryStartArea = stringMemory; // Set the end of repeatable area as one character before the last // character in Template file. // stringMemoryEndArea = stringMemoryEndOld - 1; stringMemory = stringMemoryStartArea; // Perform the normal mapping code here. stringEmbeddedImages = ""; //? nRC = CopyWithInsertMemoryArea( vResultSet, stringMemoryStartArea, stringMemoryEndArea, //? stringMemoryNew, "", stringMemoryNewHold, //? lTotalOutputSize, stringEmbeddedImages, nMimeType ); if (nRC < 0) return nRC; // Finally copy the closing brace to the output file. // stringMemoryNew = stringMemoryEndArea; TODO This is all wrong ... recode correctly in Java when needed // stringMemory++; // stringMemoryNew++; // lLthNew = (int) (stringMemoryNew - stringMemoryStartEmailBody); TODO This is all wrong ... recode correctly in Java when needed m_ZDRVROPR.CreateSeeMessage(lConnection, stringSMTPServer, stringSenderEMailAddress, stringRecipientEMailAddress, "", "", stringSubjectLine, nMimeType, stringMemoryStartEmailBody, stringAltMemory, stringEmbeddedImages, nHasAttachment, stringAttachmentFileName, stringEMailUserName, stringEMailPassword); // SysOpenFile( stringAttachmentFileName, COREFILE_DELETE ); } } nRC = SetCursorNextEntity(vResultSet, stringRootEntityName, ""); } m_ZDRVROPR.CloseSeeConnection(lConnection); //? SysFreeMemory( selMemory ); //? SysFreeMemory( selMemoryNew ); if (lAltTemplateLth != 0) { //? SysFreeMemory( selAltMemory ); //? SysFreeMemory( selAltMemoryNew ); } // DrFreeTaskMemory( stringMemoryStartOld ); // DrFreeTaskMemory( stringMemoryNewHold ); return 0; }
From source file:org.apache.drill.common.expression.fn.JodaDateValidator.java
/** * Replaces all postgres patterns from {@param pattern}, * available in postgresToJodaMap keys to jodaTime equivalents. * * @param pattern date pattern in postgres format * @return date pattern with replaced patterns in joda format *//*w w w .ja v a 2 s.c om*/ public static String toJodaFormat(String pattern) { // replaces escape character for text delimiter StringBuilder builder = new StringBuilder( pattern.replaceAll(POSTGRES_ESCAPE_CHARACTER, JODA_ESCAPE_CHARACTER)); int start = 0; // every time search of postgres token in pattern will start from this index. int minPos; // min position of the longest postgres token do { // finds first value with max length minPos = builder.length(); PostgresDateTimeConstant firstMatch = null; for (PostgresDateTimeConstant postgresPattern : postgresToJodaMap.keySet()) { // keys sorted in length decreasing // at first search longer tokens to consider situation where some tokens are the parts of large tokens // example: if pattern contains a token "DDD", token "DD" would be skipped, as a part of "DDD". int pos; // some tokens can't be in upper camel casing, so we ignore them here. // example: DD, DDD, MM, etc. if (postgresPattern.hasCamelCasing()) { // finds postgres tokens in upper camel casing // example: Month, Mon, Day, Dy, etc. pos = builder.indexOf(StringUtils.capitalize(postgresPattern.getName()), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // finds postgres tokens in lower casing pos = builder.indexOf(postgresPattern.getName().toLowerCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } // finds postgres tokens in upper casing pos = builder.indexOf(postgresPattern.getName().toUpperCase(), start); if (pos >= 0 && pos < minPos) { firstMatch = postgresPattern; minPos = pos; if (minPos == start) { break; } } } // replaces postgres token, if found and it does not escape character if (minPos < builder.length() && firstMatch != null) { String jodaToken = postgresToJodaMap.get(firstMatch); // checks that token is not a part of escape sequence if (StringUtils.countMatches(builder.subSequence(0, minPos), JODA_ESCAPE_CHARACTER) % 2 == 0) { int offset = minPos + firstMatch.getName().length(); builder.replace(minPos, offset, jodaToken); start = minPos + jodaToken.length(); } else { int endEscapeCharacter = builder.indexOf(JODA_ESCAPE_CHARACTER, minPos); if (endEscapeCharacter >= 0) { start = endEscapeCharacter; } else { break; } } } } while (minPos < builder.length()); return builder.toString(); }
From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java
protected static void checkEnvelope(MailEnvelope env, String sender, List<String> recipients, String msg) throws IOException { assertEquals(sender, env.getSender().toString()); List<MailAddress> envRecipients = env.getRecipients(); assertEquals(recipients.size(), envRecipients.size()); for (int i = 0; i < recipients.size(); i++) { MailAddress address = envRecipients.get(i); assertEquals(recipients.get(i), address.toString()); }/*from www . java 2 s.co m*/ BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(env.getMessageInputStream())); String line = null; boolean start = false; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { if (line.startsWith("Subject")) { start = true; } if (start) { sb.append(line); sb.append("\r\n"); } } String msgQueued = sb.subSequence(0, sb.length() - 2).toString(); assertEquals(msg.length(), msgQueued.length()); for (int i = 0; i < msg.length(); i++) { assertEquals(msg.charAt(i), msgQueued.charAt(i)); } } finally { if (reader != null) { reader.close(); } } }
From source file:org.apache.nifi.controller.repository.StandardProcessSession.java
private String summarizeEvents(final Checkpoint checkpoint) { final Map<Relationship, Set<String>> transferMap = new HashMap<>(); // relationship to flowfile ID's final Set<String> modifiedFlowFileIds = new HashSet<>(); int largestTransferSetSize = 0; for (final Map.Entry<FlowFileRecord, StandardRepositoryRecord> entry : checkpoint.records.entrySet()) { final FlowFile flowFile = entry.getKey(); final StandardRepositoryRecord record = entry.getValue(); final Relationship relationship = record.getTransferRelationship(); if (Relationship.SELF.equals(relationship)) { continue; }/*from w w w . j a va2s . c om*/ Set<String> transferIds = transferMap.get(relationship); if (transferIds == null) { transferIds = new HashSet<>(); transferMap.put(relationship, transferIds); } transferIds.add(flowFile.getAttribute(CoreAttributes.UUID.key())); largestTransferSetSize = Math.max(largestTransferSetSize, transferIds.size()); final ContentClaim workingClaim = record.getWorkingClaim(); if (workingClaim != null && workingClaim != record.getOriginalClaim() && record.getTransferRelationship() != null) { modifiedFlowFileIds.add(flowFile.getAttribute(CoreAttributes.UUID.key())); } } final int numRemoved = checkpoint.removedFlowFiles.size(); final int numModified = modifiedFlowFileIds.size(); final int numCreated = checkpoint.createdFlowFiles.size(); final StringBuilder sb = new StringBuilder(512); if (!LOG.isDebugEnabled() && (largestTransferSetSize > VERBOSE_LOG_THRESHOLD || numModified > VERBOSE_LOG_THRESHOLD || numCreated > VERBOSE_LOG_THRESHOLD || numRemoved > VERBOSE_LOG_THRESHOLD)) { if (numCreated > 0) { sb.append("created ").append(numCreated).append(" FlowFiles, "); } if (numModified > 0) { sb.append("modified ").append(modifiedFlowFileIds.size()).append(" FlowFiles, "); } if (numRemoved > 0) { sb.append("removed ").append(numRemoved).append(" FlowFiles, "); } for (final Map.Entry<Relationship, Set<String>> entry : transferMap.entrySet()) { if (entry.getKey() != null) { sb.append("Transferred ").append(entry.getValue().size()).append(" FlowFiles"); final Relationship relationship = entry.getKey(); if (relationship != Relationship.ANONYMOUS) { sb.append(" to '").append(relationship.getName()).append("', "); } } } } else { if (numCreated > 0) { sb.append("created FlowFiles ").append(checkpoint.createdFlowFiles).append(", "); } if (numModified > 0) { sb.append("modified FlowFiles ").append(modifiedFlowFileIds).append(", "); } if (numRemoved > 0) { sb.append("removed FlowFiles ").append(checkpoint.removedFlowFiles).append(", "); } for (final Map.Entry<Relationship, Set<String>> entry : transferMap.entrySet()) { if (entry.getKey() != null) { sb.append("Transferred FlowFiles ").append(entry.getValue()); final Relationship relationship = entry.getKey(); if (relationship != Relationship.ANONYMOUS) { sb.append(" to '").append(relationship.getName()).append("', "); } } } } if (sb.length() > 2 && sb.subSequence(sb.length() - 2, sb.length()).equals(", ")) { sb.delete(sb.length() - 2, sb.length()); } // don't add processing time if we did nothing, because we don't log the summary anyway if (sb.length() > 0) { final long processingNanos = checkpoint.processingTime; sb.append(", Processing Time = "); formatNanos(processingNanos, sb); } return sb.toString(); }
From source file:org.dataconservancy.packaging.tool.impl.generator.RemediationUtil.java
/** * Searches the supplied {@code packageResourcePath} for reserved path prefixes that should <em>not</em> be subject * to remediation, and removes them from the {@code packageResourcePath}. The location of {@link PackageResourceType * package resources} are specified by the BagIt specification and the Data Conservancy BagIt profile, and * therefore:/*from w w w .j a va 2 s .c o m*/ * <ol> * <li>May be assumed to <em>not</em> violate the specification or profile (e.g. paths defined by the * specification will never have a path component greater than 255 characters, or contain illegal * characters)</li> * <li>Must not be subject to remediation (e.g. truncation remediation shall not truncate a portion of the * reserved path)</li> * </ol> * * @param packageResourcePath the full path of the resource in the package, relative to the base directory of the * package * @return the portion of the {@code packageResourcePath} that <em>must</em> be preserved from remediation * (may be empty) */ private static StringBuilder preservePrefix(StringBuilder packageResourcePath) { for (String reserved : RESERVED_PATHS) { final int index = packageResourcePath.indexOf(reserved); if (index < 0) { // nothing to preserve, as the reserved path doesn't exist in the string being remediated continue; } // Preserve everything from index 0 in the string being remediated to the ending of the path being preserved // this is a bit greedy, but it does handle the case where the reserved path doesn't start with a /, and // the string being remediated does. StringBuilder preserved = new StringBuilder( packageResourcePath.subSequence(0, index + reserved.length())); packageResourcePath.delete(0, index + reserved.length()); return preserved; } return new StringBuilder(); }