public void testIsNotEmpty() { assertEquals(false, StringUtils.isNotEmpty(null)); assertEquals(false, StringUtils.isNotEmpty("")); assertEquals(true, StringUtils.isNotEmpty(" ")); assertEquals(true, StringUtils.isNotEmpty("foo")); assertEquals(true, StringUtils.isNotEmpty(" foo ")); }
/** * Assert that the given text does not contain the given substring. * * <pre class="code">Assert.doesNotContain(name, "rod", "Name must not contain 'rod'");</pre> * * @param textToSearch the text to search * @param substring the substring to find within the text * @param message the exception message to use if the assertion fails */ public static void doesNotContain(String textToSearch, String substring, String message) { if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) { throw new AppException(message); } }
@Test public void testQuoteIfString() { assertEquals("'myString'", StringUtils.quoteIfString("myString")); assertEquals("''", StringUtils.quoteIfString("")); assertEquals(new Integer(5), StringUtils.quoteIfString(5)); assertNull(StringUtils.quoteIfString(null)); }
/** * Search specific element by key and tagName. * * @param root root element * @param key search keyword * @param tagName search tag name * @return search result, null of either input is invalid or the looking result is not found. */ private Element searchForKey(final Element root, final String key, final String tagName) { if (root == null || StringUtils.isEmptyString(key)) { return null; } final Queue<Element> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { final Element pe = queue.poll(); final NodeList pchildrenList = pe.getChildNodes(); for (int i = 0; i < pchildrenList.getLength(); i++) { final Node node = pchildrenList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { queue.offer((Element) node); } } String value = pe.getNodeName(); if (StringUtils.isEmptyString(value) || !value.equals(tagName)) { continue; } value = pe.getAttribute(ATTRIBUTE_NAME_NAME); if (StringUtils.isEmptyString(value)) { continue; } if (value.equals(key)) { return pe; } } return null; }
@Override @SuppressWarnings({"unchecked", "rawtypes"}) public void execute( Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Site site = FrontUtils.getSite(env); List<Content> list = getList(params, env); Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params); paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list)); Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap); InvokeType type = DirectiveUtils.getInvokeType(params); String listStyle = DirectiveUtils.getString(PARAM_STYLE_LIST, params); if (InvokeType.sysDefined == type) { if (StringUtils.isBlank(listStyle)) { throw new ParamsRequiredException(PARAM_STYLE_LIST); } env.include(TPL_STYLE_LIST + listStyle + TPL_SUFFIX, UTF8, true); } else if (InvokeType.userDefined == type) { if (StringUtils.isBlank(listStyle)) { throw new ParamsRequiredException(PARAM_STYLE_LIST); } FrontUtils.includeTpl(TPL_STYLE_LIST, site, env); } else if (InvokeType.custom == type) { FrontUtils.includeTpl(TPL_NAME, site, params, env); } else if (InvokeType.body == type) { body.render(env.getOut()); } else { throw new RuntimeException("invoke type not handled: " + type); } DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap); }
@Test public void testNotEmpty() { assertFalse(StringUtils.notEmpty("")); assertFalse(StringUtils.notEmpty(null)); assertTrue(StringUtils.notEmpty(" ")); assertTrue(StringUtils.notEmpty("a")); }
public static int computeDistance(String s1, String s2) { // normalize two strings s1 = StringUtils.normalizeString(s1); s2 = StringUtils.normalizeString(s2); int[] costs = new int[s2.length() + 1]; for (int i = 0; i <= s1.length(); i++) { int lastValue = i; for (int j = 0; j <= s2.length(); j++) { if (i == 0) { costs[j] = j; } else { if (j > 0) { int newValue = costs[j - 1]; if (s1.charAt(i - 1) != s2.charAt(j - 1)) { newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; } costs[j - 1] = lastValue; lastValue = newValue; } } } if (i > 0) { costs[s2.length()] = lastValue; } } return costs[s2.length()]; }
// Sends the help page for /citizens help public static void sendHelpPage(CommandSender sender, int page) { switch (page) { case 1: header(sender, "General", 1, 2); sender.sendMessage( ChatColor.GREEN + " []" + StringUtils.wrap(" - required") + " ()" + StringUtils.wrap(" - optional")); format(sender, "citizens", "", "display Citizens information"); format(sender, "citizens", "reload", "reload Citizens files"); format(sender, "citizens", "save", "force a save of Citizens files"); format(sender, "citizens", "debug", "toggle Citizens debug mode"); format(sender, "citizens", "clean", "remove ghost NPCs"); format(sender, "toggle", "help (page)", "view available toggleable types"); format(sender, "toggle", "[type]", "toggle an NPC type"); format(sender, "toggle", "all [on/off]", "toggle all types for an NPC"); break; case 2: header(sender, "General", 2, 2); format(sender, "npc", "help [page]", "basic NPC help pages"); format(sender, "[type]", "help", "view the help page for an NPC type"); footer(sender); break; default: sender.sendMessage(MessageUtils.getMaxPagesMessage(page, 2)); break; } }
/** * Try to make a database connection to the given URL. The driver should return "null" if it * realizes it is the wrong kind of driver to connect to the given URL. This will be common, as * when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each * loaded driver in turn. * * <p>The driver should raise an SQLException if it is the right driver to connect to the given * URL, but has trouble connecting to the database. * * <p>The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as * connection arguments. * * <p>My protocol takes the form: * * <PRE> * * jdbc:mysql://host:port/database * * </PRE> * * @param url the URL of the database to connect to * @param info a list of arbitrary tag/value pairs as connection arguments * @return a connection to the URL or null if it isnt us * @exception SQLException if a database access error occurs * @see java.sql.Driver#connect */ public java.sql.Connection connect(String url, Properties info) throws SQLException { if (url != null) { if (StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)) { return connectLoadBalanced(url, info); } else if (StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) { return connectReplicationConnection(url, info); } } Properties props = null; if ((props = parseURL(url, info)) == null) { return null; } try { Connection newConn = new com.mysql.jdbc.Connection(host(props), port(props), props, database(props), url); return newConn; } catch (SQLException sqlEx) { // Don't wrap SQLExceptions, throw // them un-changed. throw sqlEx; } catch (Exception ex) { throw SQLError.createSQLException( Messages.getString("NonRegisteringDriver.17") // $NON-NLS-1$ + ex.toString() + Messages.getString("NonRegisteringDriver.18"), // $NON-NLS-1$ SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); } }
private void annotateMatched(List<CoreLabel> tokens) { List<SequenceMatchResult<CoreMap>> matched = multiPatternMatcher.findNonOverlapping(tokens); for (SequenceMatchResult<CoreMap> m : matched) { Entry entry = patternToEntry.get(m.pattern()); // Check if we will overwrite the existing annotation with this annotation int g = entry.annotateGroup; int start = m.start(g); int end = m.end(g); boolean overwriteOriginalNer = checkPosTags(tokens, start, end); if (overwriteOriginalNer) { overwriteOriginalNer = checkOrigNerTags(entry, tokens, start, end); } if (overwriteOriginalNer) { for (int i = start; i < end; i++) { tokens.get(i).set(CoreAnnotations.NamedEntityTagAnnotation.class, entry.type); } } else { if (verbose) { System.err.println( "Not annotating '" + m.group(g) + "': " + StringUtils.joinFields( m.groupNodes(g), CoreAnnotations.NamedEntityTagAnnotation.class) + " with " + entry.type + ", sentence is '" + StringUtils.joinWords(tokens, " ") + '\''); } } } }
/** * Convenience method for turning a byte[] into a string with the given encoding. * * @param encoding the Java encoding name for the byte[] -> char conversion * @param conn the MySQLConnection that created the result set * @param value the String value as a series of bytes, encoded using "encoding" * @param offset where to start the decoding * @param length how many bytes to decode * @return the String as decoded from bytes with the given encoding * @throws SQLException if an error occurs */ protected String getString( String encoding, MySQLConnection conn, byte[] value, int offset, int length) throws SQLException { String stringVal = null; if ((conn != null) && conn.getUseUnicode()) { try { if (encoding == null) { stringVal = StringUtils.toString(value); } else { SingleByteCharsetConverter converter = conn.getCharsetConverter(encoding); if (converter != null) { stringVal = converter.toString(value, offset, length); } else { stringVal = StringUtils.toString(value, offset, length, encoding); } } } catch (java.io.UnsupportedEncodingException E) { throw SQLError.createSQLException( Messages.getString("ResultSet.Unsupported_character_encoding____101") // $NON-NLS-1$ + encoding + "'.", "0S100", this.exceptionInterceptor); } } else { stringVal = StringUtils.toAsciiString(value, offset, length); } return stringVal; }
/** * Line endings can be an issue when running tests on different OSs. This function standardizes * the line endings to use <code>\n</code> * * <p>It will get the text from the given editor, change the line endings, and then save the * editor * * @param editor standardize the line endings of the text presented in this editor. */ private static void standardizeLineEndings(ITextEditor editor) { IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput()); String contents = doc.get(); contents = StringUtils.replace(contents, "\r\n", "\n"); contents = StringUtils.replace(contents, "\r", "\n"); doc.set(contents); }
/** * 新闻超链接点击跳转 * * @param context */ public static void showNewsRedirect(Context context, News news) { String url = news.getUrl(); // url为空-旧方法 if (StringUtils.isEmpty(url)) { int newsId = news.getId(); int newsType = news.getNewType().type; String objId = news.getNewType().attachment; switch (newsType) { case News.NEWSTYPE_NEWS: showNewsDetail(context, newsId); break; case News.NEWSTYPE_SOFTWARE: showSoftwareDetail(context, objId); break; case News.NEWSTYPE_POST: showQuestionDetail(context, StringUtils.toInt(objId)); break; case News.NEWSTYPE_BLOG: showBlogDetail(context, StringUtils.toInt(objId)); break; } } else { showUrlRedirect(context, url); } }
public void testIsNotBlank() { assertEquals(false, StringUtils.isNotBlank(null)); assertEquals(false, StringUtils.isNotBlank("")); assertEquals(false, StringUtils.isNotBlank(StringUtilsTest.WHITESPACE)); assertEquals(true, StringUtils.isNotBlank("foo")); assertEquals(true, StringUtils.isNotBlank(" foo ")); }
@Test public void testPartition() { String target = "request:hoge"; List<String> actual = StringUtils.partition(1, ':', target); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("request")); assertThat(actual.get(1), is("hoge")); target = "request"; actual = StringUtils.partition(1, ':', target); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("request")); assertNull(actual.get(1)); target = "request:hoge:attr"; actual = StringUtils.partition(1, ':', target); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("request")); assertThat(actual.get(1), is("hoge:attr")); target = "request:hoge:attr:bar"; actual = StringUtils.partition(1, ':', target); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("request")); assertThat(actual.get(1), is("hoge:attr:bar")); target = "request:hoge:attr"; actual = StringUtils.partition(2, ':', target); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("request:hoge")); assertThat(actual.get(1), is("attr")); }
/** * Test the Base64OutputStream implementation * * @throws Exception for some failure scenarios. */ @Test public void testBase64OutputStreamByChunk() throws Exception { // Hello World test. byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n"); byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE); testByChunk(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); // Single Byte test. encoded = StringUtils.getBytesUtf8("AA==\r\n"); decoded = new byte[] {(byte) 0}; testByChunk(encoded, decoded, BaseNCodec.MIME_CHUNK_SIZE, CRLF); // OpenSSL interop test. encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE); decoded = Base64TestData.DECODED; testByChunk(encoded, decoded, BaseNCodec.PEM_CHUNK_SIZE, LF); // Single Line test. String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", ""); encoded = StringUtils.getBytesUtf8(singleLine); decoded = Base64TestData.DECODED; testByChunk(encoded, decoded, 0, LF); // test random data of sizes 0 thru 150 for (int i = 0; i <= 150; i++) { byte[][] randomData = Base64TestData.randomData(i, false); encoded = randomData[1]; decoded = randomData[0]; testByChunk(encoded, decoded, 0, LF); } }
/** * Parse the parameters of a connection into a CoreNLP properties file that can be passed into * {@link StanfordCoreNLP}, and used in the I/O stages. * * @param httpExchange The http exchange; effectively, the request information. * @return A {@link Properties} object corresponding to a combination of default and passed * properties. * @throws UnsupportedEncodingException Thrown if we could not decode the key/value pairs with * UTF-8. */ private Properties getProperties(HttpExchange httpExchange) throws UnsupportedEncodingException { // Load the default properties Properties props = new Properties(); defaultProps .entrySet() .stream() .forEach( entry -> props.setProperty(entry.getKey().toString(), entry.getValue().toString())); // Try to get more properties from query string. Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI()); if (urlParams.containsKey("properties")) { StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8")) .entrySet() .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue())); } else if (urlParams.containsKey("props")) { StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8")) .entrySet() .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue())); } // Make sure the properties compile props.setProperty( "annotators", StanfordCoreNLP.ensurePrerequisiteAnnotators( props.getProperty("annotators").split("[, \t]+"))); return props; }
/** * Loads this properties data from this string. * * @param propertiesData The string containing the properties data. * @return The matching properties object. * @throws IOException when the data could not be read. */ public static Properties loadPropertiesFromString(String propertiesData) throws IOException { Properties properties = new Properties(); BufferedReader in = new BufferedReader(new StringReader(propertiesData)); while (true) { String line = in.readLine(); if (line == null) { return properties; } line = StringUtils.trimLeadingWhitespace(line); if (line.length() > 0) { char firstChar = line.charAt(0); if (firstChar != '#' && firstChar != '!') { while (endsWithContinuationMarker(line)) { String nextLine = in.readLine(); line = line.substring(0, line.length() - 1); if (nextLine != null) { line += StringUtils.trimLeadingWhitespace(nextLine); } } int separatorIndex = line.indexOf("="); if (separatorIndex == -1) { separatorIndex = line.indexOf(":"); } String key = (separatorIndex != -1 ? line.substring(0, separatorIndex) : line); String value = (separatorIndex != -1) ? line.substring(separatorIndex + 1) : ""; key = StringUtils.trimTrailingWhitespace(key); value = StringUtils.trimLeadingWhitespace(value); properties.put(unescape(key), unescape(value)); } } } }
@Test public void testValidateHtml() { // check for null handling String expected = null; String actual = StringUtils.validateHtml(expected); Assert.assertEquals(expected, actual); // check for empty string handling expected = ""; actual = StringUtils.validateHtml(expected); Assert.assertNull(actual); // check unclosed tags expected = "<input type=something that is not correct"; actual = StringUtils.validateHtml(expected); Assert.assertNotNull(actual); Assert.assertNotSame(expected, actual); // check invalid tags expected = "<p>This paragraph is <b>not</p> correct!</b>"; Assert.assertNotNull(actual); Assert.assertNotSame(expected, actual); // check closing html block expected = "</body></html>"; Assert.assertNotNull(actual); Assert.assertNotSame(expected, actual); }
/** * Dumps this list of metaDataTableRows in the log file. * * @param metaDataTableRows The list of metaDataTableRows to dump. */ public static void dumpMigrations(List<MetaDataTableRow> metaDataTableRows) { LOG.info("+-------------+------------------------+---------------------+---------+"); LOG.info("| Version | Description | Installed on | State |"); LOG.info("+-------------+------------------------+---------------------+---------+"); if (metaDataTableRows.isEmpty()) { LOG.info("| No migrations applied yet |"); } else { for (MetaDataTableRow metaDataTableRow : metaDataTableRows) { LOG.info( "| " + StringUtils.trimOrPad(metaDataTableRow.getVersion().toString(), 11) + " | " + StringUtils.trimOrPad(metaDataTableRow.getDescription(), 22) + " | " + StringUtils.trimOrPad( DateUtils.formatDateAsIsoString(metaDataTableRow.getInstalledOn()), 19) + " | " + StringUtils.trimOrPad(metaDataTableRow.getState().name(), 7) + " |"); } } LOG.info("+-------------+------------------------+---------------------+---------+"); }
@Override protected boolean composeNative(String to, String subject, String body, File... attachments) throws IOException, InterruptedException { final Process process = Runtime.getRuntime().exec(new String[] {"osascript"}); final PrintStream w = new PrintStream(new BufferedOutputStream(process.getOutputStream())); // use ID to handle application renaming (always a slight delay after a rename for // this to work, though) w.println("tell application id \"" + AppleMailBundleID + "\""); w.println( " set theMessage to make new outgoing message with properties {" + getAppleMailParam(subject, body) + "}"); if (to != null) w.println( " tell theMessage to make new to recipient with properties {address:" + StringUtils.doubleQuote(to) + "}"); for (File attachment : attachments) { w.println( " tell content of theMessage to make new attachment with properties {file name:" + StringUtils.doubleQuote(attachment.getAbsolutePath()) + "} at after last paragraph"); } w.println("end tell"); w.close(); if (w.checkError()) throw new IOException(); final int returnCode = process.waitFor(); if (returnCode != 0) throw new IllegalStateException("Non zero return code: " + returnCode); return true; }
/** * @param prop String property to search * @param propFile the pro file * @return the property value */ public static String getProp(String prop, File propFile) { BufferedReader br = null; String value = null; try { DataInputStream dis = new DataInputStream(new FileInputStream(propFile)); br = new BufferedReader( new InputStreamReader( new BufferedInputStream(dis), Charset.forName("UTF-8").newDecoder())); String line; while ((line = br.readLine()) != null) { if (line.length() > 0 && line.charAt(0) != '#' && line.lastIndexOf("=") > 0) { String tmpProp = StringUtils.getCropString(line, line.lastIndexOf("=")); tmpProp = StringUtils.removeSpaces(tmpProp); if (tmpProp.equals(prop)) { value = StringUtils.getSubString(line, line.lastIndexOf("=")); dis.close(); break; } } } } catch (Exception e) { e.printStackTrace(); } // make sure we close the input stream try { br.close(); } catch (IOException e) { e.printStackTrace(); } return value; }
public void replacePointMarkersOnLine() { int width = getWidth(); int height = getHeight(); for (int yi = 0; yi < height; yi++) { for (int xi = 0; xi < width; xi++) { char c = get(xi, yi); Cell cell = new Cell(xi, yi); if (StringUtils.isOneOf(c, pointMarkers) && isStarOnLine(cell)) { boolean isOnHorizontalLine = false; if (StringUtils.isOneOf(get(cell.getEast()), horizontalLines)) isOnHorizontalLine = true; if (StringUtils.isOneOf(get(cell.getWest()), horizontalLines)) isOnHorizontalLine = true; boolean isOnVerticalLine = false; if (StringUtils.isOneOf(get(cell.getNorth()), verticalLines)) isOnVerticalLine = true; if (StringUtils.isOneOf(get(cell.getSouth()), verticalLines)) isOnVerticalLine = true; if (isOnHorizontalLine && isOnVerticalLine) { set(xi, yi, '+'); if (DEBUG) System.out.println("replaced marker on line '" + c + "' with +"); } else if (isOnHorizontalLine) { set(xi, yi, '-'); if (DEBUG) System.out.println("replaced marker on line '" + c + "' with -"); } else if (isOnVerticalLine) { set(xi, yi, '|'); if (DEBUG) System.out.println("replaced marker on line '" + c + "' with |"); } } } } }
@Test public void testIsEmpty() { Assert.assertTrue(StringUtils.isEmpty("")); Assert.assertTrue(StringUtils.isEmpty(null)); Assert.assertFalse(StringUtils.isEmpty("a")); }
/** * 获取一个对象的属性值(除了传统的Getter,还可以容忍PUBLIC Field)。<br> * </> 不查找方法(没有使用CE),直接尝试调用一个对象各类可能的方法(多是getter应用)<br> * </> 按照 obj.property. obj.getProperty(), obj.isProperty(), obj.property(),. 的顺序依次尝试执行 如果有异常扔出 * FailToInvokingException * * @param object 实际对象本身 * @param property 对象的属性 * @return 对象的属性值 */ public static Object getPropertyValue(Object object, String property) { Class<?> clzz = object.getClass(); try { Field fld = object.getClass().getField(property); return fld.get(object); } catch (Throwable t) { Method m = null; try { m = clzz.getMethod("get" + StringUtils.capitalize(property)); } catch (NoSuchMethodException t1) { try { m = clzz.getMethod("is" + StringUtils.capitalize(property)); } catch (NoSuchMethodException t2) { try { m = clzz.getMethod(property); } catch (NoSuchMethodException e) { throw new FailToGetValueException( "Can NOT find any public property or getter named [ %s ] on class[ %s ]", property, object.getClass()); } } } try { return m.invoke(object); } catch (Throwable e) { throw new FailToGetValueException( e, "Get property[%s] value on class[%s] failed.", property, object.getClass()); } } }
@Test public void defaultString() { Assert.assertNull(StringUtils.defaultString(null, null)); Assert.assertEquals(StringUtils.defaultString(null, shortString), shortString); Assert.assertEquals(StringUtils.defaultString(shortString, null), shortString); Assert.assertEquals(StringUtils.defaultString(shortString, shortString), shortString); }
public static ArrayList<ArticleData> readJArticlesFromFile(String path) throws ParserConfigurationException, SAXException, IOException, ParseException { ArrayList<ArticleData> result = new ArrayList<ArticleData>(); File file = new File(path); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("art"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { ArticleData article = new ArticleData(); Element fstElmnt = (Element) fstNode; article.acc = Integer.parseInt(fstElmnt.getAttribute("ac")); article.refId = Integer.parseInt(fstElmnt.getAttribute("id")); article.pub = Boolean.getBoolean(fstElmnt.getAttribute("published")); article.translationType = PMDataTypes.DITT_JARTICLE; article.title = StringUtils.getXMLFromElement(fstElmnt, "title"); article.www = StringUtils.getXMLFromElement(fstElmnt, "www"); result.add(article); } } return result; }
@Test public void testJoin() { assertThat(StringUtils.join(',', "a", "b", "c"), is("a,b,c")); assertThat(StringUtils.join(',', "a"), is("a")); assertThat(StringUtils.join(',', "a", "b", "c,"), is("a,b,c,")); assertThat(StringUtils.join(','), is("")); }
/** * 从文件读取json字符串 * * @param path 目录 * @param name 文件名称 * @return 返回字符串 */ public static String readJsonFromFile(String path, String name) { if (StringUtils.isEmpty(path) || StringUtils.isEmpty(name)) { return null; } String content = ""; File file = new File(path + name); if (!file.exists()) { return null; } InputStream in = null; try { in = new FileInputStream(file); if (in != null) { InputStreamReader inputreader = new InputStreamReader(in); BufferedReader buffreader = new BufferedReader(inputreader); String line; // 分行读取 while ((line = buffreader.readLine()) != null) { content += line; } in.close(); } } catch (IOException e) { e.printStackTrace(); return null; } return content; }
public BulkSQLLoader_Direct(Connection conn, String schema, String table, String[] fieldNames) throws RemoteException { super(conn, schema, table, fieldNames); try { prevAutoCommit = conn.getAutoCommit(); if (prevAutoCommit) conn.setAutoCommit(false); String quotedTable = SQLUtils.quoteSchemaTable(conn, schema, table); String[] columns = new String[fieldNames.length]; for (int i = 0; i < fieldNames.length; i++) columns[i] = SQLUtils.quoteSymbol(conn, fieldNames[i]); baseQuery = String.format( "INSERT INTO %s(%s) VALUES ", quotedTable, StringUtils.join(",", columns)); rowQuery = "(" + StringUtils.mult(",", "?", fieldNames.length) + ")"; rowBuffer = new Vector<Object[]>(setQueryRowCount(DEFAULT_BUFFER_SIZE)); } catch (SQLException e) { throw new RemoteException("Error initializing BulkSQLLoader_Direct", e); } }