/** Parses input stream and creates new <code>HttpRequest</code> object. */ public static HttpRequest readFrom(InputStream in) { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(in, StringPool.ISO_8859_1)); } catch (UnsupportedEncodingException uneex) { return null; } HttpRequest httpRequest = new HttpRequest(); String line; try { line = reader.readLine(); } catch (IOException ioex) { throw new HttpException(ioex); } if (!StringUtil.isBlank(line)) { String[] s = StringUtil.splitc(line, ' '); httpRequest.method(s[0]); httpRequest.path(s[1]); httpRequest.httpVersion(s[2]); httpRequest.readHeaders(reader); httpRequest.readBody(reader); } return httpRequest; }
public Map<String, Object> getVariableMap() { Map<String, Object> vars = new HashMap<String, Object>(); ConvertUtils.register(new DateConverter(), java.util.Date.class); if (StringUtil.isBlank(keys)) { return vars; } String[] arrayKey = keys.split(","); String[] arrayValue = values.split(","); String[] arrayType = types.split(","); for (int i = 0; i < arrayKey.length; i++) { if ("".equals(arrayKey[i]) || "".equals(arrayValue[i]) || "".equals(arrayType[i])) { continue; } String key = arrayKey[i]; String value = arrayValue[i]; String type = arrayType[i]; Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue(); Object objectValue = ConvertUtils.convert(value, targetType); vars.put(key, objectValue); } return vars; }
/** Adds byte content into the zip as a file. */ public static void addToZip(ZipOutputStream zos, byte[] content, String path, String comment) throws IOException { while (path.length() != 0 && path.charAt(0) == '/') { path = path.substring(1); } if (StringUtil.endsWithChar(path, '/')) { path = path.substring(0, path.length() - 1); } ZipEntry zipEntry = new ZipEntry(path); zipEntry.setTime(System.currentTimeMillis()); if (comment != null) { zipEntry.setComment(comment); } zos.putNextEntry(zipEntry); InputStream is = new ByteArrayInputStream(content); try { StreamUtil.copy(is, zos); } finally { StreamUtil.close(is); } zos.closeEntry(); }
public Map<String, ScoredElement<UrlItem>> getPossiblePageUrls(Node[] allLink, String type) throws MalformedURLException { Map<String, ScoredElement<UrlItem>> possibleLinks = new HashMap<String, ScoredElement<UrlItem>>(); for (Node link : allLink) { String href = link.getAttribute("href"); if (StringUtil.isEmpty(href)) { continue; } href = href.replaceAll("#.*$", ""); href = href.replaceAll("/$", ""); href = Util.getAbsouluteUrl(href, currentUrl); if (currentUrl.getUrl().equals(href)) { continue; } String base = "://" + currentUrl.getUri().getHost(); if (href.indexOf(base) == -1) { continue; } int score = getPageUrlScore(href, link, type); UrlItem url = new UrlItem(href); ScoredElement<UrlItem> element = new ScoredElement<UrlItem>(score, url); possibleLinks.put(url.getKey(), element); } return possibleLinks; }
public static boolean validate(Object value, String substring, boolean ignoreCase) { if (value == null) { return true; } if (ignoreCase) { return StringUtil.indexOfIgnoreCase(value.toString(), substring) > -1; } return value.toString().indexOf(substring) > -1; }
/** * 为返回结果data中添加一行redirect_url记录,用于定位跳转页面 * * @param url * @return */ public ResultObject returnWithRedirectUrl(String url) { /// 如果跳转url不为空,则记录需要跳转的url if (this.data == null) { this.data = new HashMap<String, Object>(); } if (!StringUtil.isBlank(url)) { this.data.put("redirect_url", url); } return this; }
private void _testHtmls(String root) throws IOException { FindFile ff = new WildcardFindFile().include("**/*.*ml"); long reps = 1; JStopWatch jsw = new JStopWatch(); boolean processed = false; while (reps-- > 0) { ff.searchPath(root); File file; while ((file = ff.nextFile()) != null) { processed = true; System.out.println('+' + file.getName()); String content = FileUtil.readString(file); String expectedResult = FileUtil.readString(new File(file.getAbsolutePath() + ".txt")); String formatted = null; File formattedFile = new File(file.getAbsolutePath() + "-fmt.htm"); if (formattedFile.exists()) { formatted = FileUtil.readString(formattedFile); } boolean isXml = file.getName().endsWith(".xml"); String[] results = _parse(content, isXml); String result = results[0]; // parsing result String result2 = results[1]; // tag writer expectedResult = StringUtil.removeChars(expectedResult, '\r'); result = StringUtil.removeChars(result, '\r').trim(); assertEquals(expectedResult, result); if (formatted != null) { assertEquals(formatted, result2); } else { assertEquals(content, result2); } } } assertTrue(processed); System.out.println(jsw); }
/** Returns IP address as integer. */ public static int getIpAsInt(String ipAddress) { int ipIntValue = 0; String[] tokens = StringUtil.splitc(ipAddress, '.'); for (String token : tokens) { if (ipIntValue > 0) { ipIntValue <<= 8; } ipIntValue += Integer.parseInt(token); } return ipIntValue; }
@Test public void testGetBytes() { try { FileInputStream in = new FileInputStream(new File(dataRoot, "file/a.txt")); byte[] data = StreamUtil.readBytes(in); StreamUtil.close(in); String s = new String(data); s = StringUtil.remove(s, '\r'); assertEquals("test file\n", s); in = new FileInputStream(new File(dataRoot, "file/a.txt")); String str = new String(StreamUtil.readChars(in)); StreamUtil.close(in); str = StringUtil.remove(str, '\r'); assertEquals("test file\n", str); } catch (FileNotFoundException e) { fail("StreamUtil.testGetBytes " + e.toString()); } catch (IOException e) { fail("StreamUtil.testGetBytes " + e.toString()); } }
/** Converts method type short names into names. */ protected String[] convertTypeNames(Method actionClassMethod) { Class[] types = actionClassMethod.getParameterTypes(); String[] names = new String[types.length]; for (int i = 0; i < types.length; i++) { Class type = types[i]; names[i] = StringUtil.uncapitalize(type.getSimpleName()); } return names; }
/** * 漂亮输出 * * @param logger 日志输出 * @param output 输出语句 * @param args 参数集合 */ public static void prettyOutput(Logger logger, String output, Object... args) { StringBuffer finalOutput = new StringBuffer(LINE_SEPARATOR); finalOutput.append("\t"); for (int i = 0; i < args.length; i++) output = StringUtil.replaceFirst(output, "{}", args[i].toString()); output = output.replace("\n", "\n\t"); output = output.replace(LINE_SEPARATOR, LINE_SEPARATOR + "\t"); output = output.replace("{nl}", LINE_SEPARATOR + "\t"); finalOutput.append(output); finalOutput.append(LINE_SEPARATOR); logger.info(finalOutput.toString()); }
@Override public void process(StringBuilder out) { if (isPreviousChunkOfType(CHUNK_TABLE)) { appendMissingSpace(out); } DbEntityDescriptor ded = tableRef != null ? lookupTableRef(tableRef) : lookupType(resolveClass(data)); out.append(SET); DbEntityColumnDescriptor[] decList = ded.getColumnDescriptors(); String typeName = StringUtil.uncapitalize(ded.getEntityName()); // String table = resolveTable(tableRef, ded); int size = 0; for (DbEntityColumnDescriptor dec : decList) { String property = dec.getPropertyName(); Object value = BeanUtil.getDeclaredProperty(data, property); if (includeColumns == COLS_ONLY_EXISTING) { if (DbOomUtil.isEmptyColumnValue(dec, value)) { continue; } } if (size > 0) { out.append(',').append(' '); } size++; // do not add table reference in set // as only one table can be updated // also, Postgress database does not allow it (see #JODD-21) // out.append(table).append('.'); out.append(dec.getColumnName()).append('='); String propertyName = typeName + '.' + property; defineParameter(out, propertyName, value, dec); } if (size > 0) { out.append(' '); } }
/** * Returns full URL path. Simply concatenates {@link #protocol(String) protocol}, {@link * #host(String) host}, {@link #port(int) port}, {@link #path(String) path} and {@link * #queryString(String) query string}. */ public String url() { StringBuilder url = new StringBuilder(); url.append(hostUrl()); if (path != null) { url.append(path); } String queryString = queryString(); if (StringUtil.isNotBlank(queryString)) { url.append('?'); url.append(queryString); } return url.toString(); }
@Test public void testCompare() { try { File file = new File(dataRoot, "file/a.txt"); FileInputStream in1 = new FileInputStream(file); String content = "test file\r\n"; if (file.length() == 10) { content = StringUtil.remove(content, '\r'); } AsciiInputStream in2 = new AsciiInputStream(content); assertTrue(StreamUtil.compare(in1, in2)); StreamUtil.close(in2); StreamUtil.close(in1); } catch (FileNotFoundException e) { fail("StreamUtil.testCloneCompare " + e.toString()); } catch (IOException e) { fail("StreamUtil.testCloneCompare " + e.toString()); } }
public static void addFolderToZip(ZipOutputStream zos, String path, String comment) throws IOException { while (path.length() != 0 && path.charAt(0) == '/') { path = path.substring(1); } // add folder record if (!StringUtil.endsWithChar(path, '/')) { path += '/'; } ZipEntry zipEntry = new ZipEntry(path); zipEntry.setTime(System.currentTimeMillis()); if (comment != null) { zipEntry.setComment(comment); } zipEntry.setSize(0); zipEntry.setCrc(0); zos.putNextEntry(zipEntry); zos.closeEntry(); }
/** * Adds single entry to ZIP output stream. * * @param zos zip output stream * @param file file or folder to add * @param path relative path of file entry; if <code>null</code> files name will be used instead * @param comment optional comment * @param recursive when set to <code>true</code> content of added folders will be added, too */ public static void addToZip( ZipOutputStream zos, File file, String path, String comment, boolean recursive) throws IOException { if (file.exists() == false) { throw new FileNotFoundException(file.toString()); } if (path == null) { path = file.getName(); } while (path.length() != 0 && path.charAt(0) == '/') { path = path.substring(1); } boolean isDir = file.isDirectory(); if (isDir) { // add folder record if (!StringUtil.endsWithChar(path, '/')) { path += '/'; } } ZipEntry zipEntry = new ZipEntry(path); zipEntry.setTime(file.lastModified()); if (comment != null) { zipEntry.setComment(comment); } if (isDir) { zipEntry.setSize(0); zipEntry.setCrc(0); } zos.putNextEntry(zipEntry); if (!isDir) { InputStream is = new FileInputStream(file); try { StreamUtil.copy(is, zos); } finally { StreamUtil.close(is); } } zos.closeEntry(); // continue adding if (recursive && file.isDirectory()) { boolean noRelativePath = StringUtil.isEmpty(path); final File[] children = file.listFiles(); if (children != null && children.length != 0) { for (File child : children) { String childRelativePath = (noRelativePath ? StringPool.EMPTY : path) + child.getName(); addToZip(zos, child, childRelativePath, comment, recursive); } } } }
public ColumnsSelectChunk(String reference) { super(CHUNK_SELECT_COLUMNS); reference = reference.trim(); int dotNdx = reference.lastIndexOf('.'); if (dotNdx == -1) { this.tableRef = reference; this.columnRef = null; this.columnRefArr = null; this.includeColumns = COLS_ALL; this.hint = null; } else { String tref = reference.substring(0, dotNdx); reference = reference.substring(dotNdx + 1); // table dotNdx = tref.lastIndexOf('.'); if (dotNdx == -1) { this.tableRef = tref; this.hint = null; } else { int doubleColumnNdx = tref.indexOf(':'); if (doubleColumnNdx == -1) { // no special hint this.tableRef = tref.substring(dotNdx + 1); this.hint = tref; } else { // hint is different this.tableRef = tref.substring(doubleColumnNdx + 1); this.hint = tref.substring(0, doubleColumnNdx); } } // column if (reference.equals(StringPool.STAR)) { this.columnRef = null; this.columnRefArr = null; this.includeColumns = COLS_ALL; } else if (reference.equals(StringPool.PLUS)) { this.columnRef = null; this.columnRefArr = null; this.includeColumns = COLS_ONLY_IDS; } else if (reference.equals(StringPool.PERCENT)) { this.columnRef = null; this.columnRefArr = null; this.includeColumns = COLS_ALL_BUT_ID; } else if (reference.length() != 0 && reference.charAt(0) == '[' && reference.charAt(reference.length() - 1) == ']') { this.columnRef = null; this.columnRefArr = StringUtil.splitc(reference.substring(1, reference.length() - 1), SPLIT); StringUtil.trimAll(this.columnRefArr); this.includeColumns = COLS_NA_MULTI; } else { this.columnRef = reference; this.columnRefArr = null; this.includeColumns = COLS_NA; } } }
/** * Creates alias from target object and target method name. If classname contains a '$' sign, * everything will be stripped after it (to get the real name, if action class is proxified). */ protected String alias(Object target, String targetMethodName) { String targetClassName = target.getClass().getName(); targetClassName = StringUtil.cutToIndexOf(targetClassName, '$'); return '<' + targetClassName + '#' + targetMethodName + '>'; }
public static boolean validate(Object value) { if (value == null) { return true; } return StringUtil.isNotBlank(value.toString()); }