List of usage examples for org.apache.commons.lang3 StringUtils substringAfter
public static String substringAfter(final String str, final String separator)
Gets the substring after the first occurrence of a separator.
From source file:org.kawanfw.file.test.parms.ProxyLoader.java
public Proxy getProxy() throws IOException, URISyntaxException { if (FrameworkSystemUtil.isAndroid()) { return null; }/*from w w w .j a v a 2s . c o m*/ System.setProperty("java.net.useSystemProxies", "true"); List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com/")); if (proxies != null && proxies.size() >= 1) { System.out.println("Proxy in use: " + proxies.get(0)); if (proxies.get(0).type().equals(Proxy.Type.DIRECT)) { return null; } System.out.println("Loading proxy file info..."); // System.setProperty("java.net.useSystemProxies", "false"); File file = new File(NEOTUNNEL_TXT); if (file.exists()) { String proxyValues = FileUtils.readFileToString(file); String username = StringUtils.substringBefore(proxyValues, " "); String password = StringUtils.substringAfter(proxyValues, " "); // proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( // "127.0.0.1", 8080)); proxy = proxies.get(0); passwordAuthentication = new PasswordAuthentication(username, password.toCharArray()); System.out.println("USING PROXY WITH AUTHENTICATION: " + proxy + " / " + username + "-" + password); } else { throw new FileNotFoundException("proxy values not found. No file " + file); } } return proxy; }
From source file:org.kawanfw.file.test.parms.TestParms.java
/** * Build the server root file from info dynamically stored in FILE_CONFIGURATOR_TXT * @return/*w ww. ja v a2s.c o m*/ */ public static String getServerRootFromFile() { try { String content = FileUtils.readFileToString(FILE_CONFIGURATOR_TXT); if (content == null || content.equals("null")) { return "c:\\"; } String root = StringUtils.substringBefore(content, "!"); String withUsername = StringUtils.substringAfter(content, "!"); if (withUsername.equals("true")) { return root + File.separator + "username" + File.separator; } else { return root + File.separator; } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.kawanfw.sql.api.client.RemoteDriver.java
/** * Attempts to make a database connection to the given URL. * /*from w w w .ja v a2s . c om*/ * The driver will return "null" if it realizes it is the wrong kind of * driver to connect to the given URL. {@link #acceptsURL} will return null. * * <P> * The driver will throw<code>SQLException</code> if it is the right driver * to connect to the given URL but has trouble connecting to the database. * * <P> * The <code>java.util.Properties</code> argument can be used to pass * arbitrary string tag/value pairs as connection arguments. At least "user" * and "password" properties should be included in the * <code>Properties</code> object. * * @param url * the URL of the database to which to connect * @param info * a list of arbitrary string tag/value pairs as connection * arguments. At least a "user" and "password" property should be * included. * @return a <code>Connection</code> object that represents a connection to * the URL * @exception SQLException * if a database access error occurs */ @Override public Connection connect(String url, Properties info) throws SQLException { if (url == null) { throw new SQLException("url not set. Please provide an url."); } if (!acceptsURL(url)) { return null; } Properties info2 = new Properties(); RemoteDriverUtil.copyProperties(info, info2); // Properties may be passed in url if (url.contains("?")) { String query = StringUtils.substringAfter(url, "?"); Map<String, String> mapProps = RemoteDriverUtil.getQueryMap(query); Set<String> set = mapProps.keySet(); for (String propName : set) { info2.setProperty(propName, mapProps.get(propName)); } url = StringUtils.substringBefore(url, "?"); } String username = info2.getProperty("user"); String password = info2.getProperty("password"); if (username == null) { throw new SQLException("user not set. Please provide a user."); } if (password == null) { throw new SQLException("password not set. Please provide a password."); } // Add proxy lookup String proxyType = info2.getProperty("proxyType"); String proxyHostname = info2.getProperty("proxyHostname"); String proxyPort = info2.getProperty("proxyPort"); String proxyUsername = info2.getProperty("proxyUsername"); String proxyPassword = info2.getProperty("proxyPassword"); String statelessMode = info2.getProperty("statelessMode"); String joinResultSetMetaData = info2.getProperty("joinResultSetMetaData"); String zipResultSet = info2.getProperty("zipResultSet"); int port = -1; Proxy proxy = null; if (proxyHostname != null) { try { port = Integer.parseInt(proxyPort); } catch (NumberFormatException e) { throw new SQLException("Invalid proxy port. Port is not numeric: " + proxyPort); } if (proxyType == null) { proxyType = "HTTP"; } proxy = new Proxy(Type.valueOf(proxyType), new InetSocketAddress(proxyHostname, port)); } boolean statelessModeBoolean = Boolean.parseBoolean(statelessMode); SessionParameters sessionParameters = getSessionParameters(info2); debug(sessionParameters.toString()); // if (url.startsWith("jdbc:kawanfw://")) { // url = url.replace("jdbc:kawanfw", "http"); // } // If we have passed the "proxy" property, build back the // instance from the property value // 1) Treat the case the user did a property.put(proxy) instead of // property.setProperty(proxy.toString()) if (proxy == null) { Object objProxy = info2.get("proxy"); if (objProxy != null && objProxy instanceof Proxy) { proxy = (Proxy) proxy; } // 2) Treat the case the user as correctly used // property.setProperty(httpProxy.toString()) else { String proxyStr = info2.getProperty("proxy"); debug("proxyStr:" + proxyStr); if (proxyStr != null) { proxy = RemoteDriverUtil.buildProxy(proxyStr); } } } // If we have passed the "sessionParameters" property, build back // the // instance from the property value // 1) Treat the case the user did a property.put(sessionParameters) // instead of property.setProperty(sessionParameters.toString()) Object objSessionParameters = info2.get("sessionParameters"); if (objSessionParameters != null && objSessionParameters instanceof SessionParameters) { String jsonString = SessionParametersGson.toJson((SessionParameters) (objSessionParameters)); if (jsonString != null) { sessionParameters = SessionParametersGson.fromJson(jsonString); } } // 2) Treat the case the user as correctly used // property.setProperty(sessionParameters.toString()) else { String jsonString = info2.getProperty("sessionParameters"); if (jsonString != null) { sessionParameters = SessionParametersGson.fromJson(jsonString); } } debug("url : " + url); debug("Proxy : " + proxy); debug("sessionParameters: " + sessionParameters); boolean doJoinResultSetMetaData = false; if (joinResultSetMetaData != null) { doJoinResultSetMetaData = Boolean.parseBoolean(joinResultSetMetaData); debug("joinResultSetMetaData: " + doJoinResultSetMetaData); } PasswordAuthentication passwordAuthentication = null; if (proxy != null && proxyUsername != null) { passwordAuthentication = new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); } boolean doZipResultSet = true; if (zipResultSet != null) { doZipResultSet = Boolean.parseBoolean(zipResultSet); debug("zipResultSet: " + doZipResultSet); } Connection connection = new RemoteConnection(url, username, password.toCharArray(), proxy, passwordAuthentication, sessionParameters, statelessModeBoolean, doJoinResultSetMetaData, doZipResultSet); return connection; }
From source file:org.kawanfw.sql.api.client.RemoteDriverUtil.java
/** * Create a Proxy instance from a Proxy.toString() representation * Example: HTTP @ www.kawansoft.com/195.154.226.82:8080 * @param proxyToString the proxy in Proxy.toString() format * @return the build proxy//from w w w.j av a 2 s .c o m */ public static Proxy buildProxy(String proxyToString) { if (proxyToString == null) { throw new NullPointerException("ip is null!"); } if (!proxyToString.contains(" @ ")) { throw new IllegalArgumentException("Malformed Proxy.toString() format: @ separator is missing."); } // Get the type String type = StringUtils.substringBefore(proxyToString, " @ "); if (type == null) { throw new IllegalArgumentException("Malformed Proxy.toString() format: no Type"); } type = type.trim(); debug("Proxy.Type.DIRECT: " + Proxy.Type.DIRECT.toString()); if (!type.equals(Proxy.Type.DIRECT.toString()) && !type.equals(Proxy.Type.HTTP.toString()) && !type.equals(Proxy.Type.SOCKS.toString())) { throw new IllegalArgumentException( "Malformed Proxy.toString() format: Type does not contain DIRECT / HTTP / SOCKS: " + type + ":"); } String hostname = null; String portStr = null; int port = 0; if (proxyToString.contains("@ /")) { // Case 1 : HTTP @ /195.154.226.82:8080 // no hostname IP only hostname = StringUtils.substringBetween(proxyToString, "/", ":"); } else { // Case 2 : HTTP @ localhost/127.0.0.1:8080 // hostname followed by ip or /subaddress hostname = StringUtils.substringBetween(proxyToString, " @ ", "/"); String ip = StringUtils.substringBetween(proxyToString, "/", ":"); // if ip string is in IP format, dont take in account the ip after / // If not, following / is the hostname if (validateIpFormat(ip)) { hostname = StringUtils.substringBetween(proxyToString, " @ ", "/"); } else { hostname = StringUtils.substringBetween(proxyToString, " @ ", ":"); } } portStr = StringUtils.substringAfter(proxyToString, ":"); if (StringUtils.isNumeric(portStr)) { port = Integer.parseInt(portStr); } else { throw new IllegalArgumentException( "Malformed Proxy.toString() format: does not contain numeric port: " + proxyToString); } Proxy proxy = new Proxy(Type.valueOf(type), new InetSocketAddress(hostname, port)); return proxy; }
From source file:org.kawanfw.sql.api.server.StatementAnalyser.java
/** * Returns the table name in use type from a DML SQL order. * /*from www. j a v a2s. com*/ * @return the table name in use (the first one in a <code>SELECT</code> * statement) for a DML statement. Returns null if statement is not * DML. */ public String getTableNameFromDmlStatement() throws IllegalArgumentException { // Extract the first order String statementTypeUpper = statementType.toUpperCase(); String sqlUpper = sql.toUpperCase(); // Extract the table depending on the ordOer sqlUpper = StringUtils.substringAfter(sqlUpper, statementTypeUpper); sqlUpper = sqlUpper.trim(); String table = null; if (statementTypeUpper.equals(INSERT)) { sqlUpper = StringUtils.substringAfter(sqlUpper, "INTO "); sqlUpper = sqlUpper.trim(); table = StringUtils.substringBefore(sqlUpper, " "); } else if (statementTypeUpper.equals(SELECT) || statementTypeUpper.equals(DELETE)) { sqlUpper = StringUtils.substringAfter(sqlUpper, "FROM "); sqlUpper = sqlUpper.trim(); // Remove commas in the statement and replace with blanks in case we // have // a join: "TABLE," ==> "TABLE " sqlUpper = sqlUpper.replaceAll(",", " "); table = StringUtils.substringBefore(sqlUpper, BLANK); } else if (statementTypeUpper.equals(UPDATE)) { debug("sqlLocal :" + sqlUpper + ":"); table = StringUtils.substringBefore(sqlUpper, BLANK); } else { return null; // No table } debug("table: " + table); if (table != null) { table = table.trim(); } // Return the part after last dot if (table.contains(".")) { table = StringUtils.substringAfterLast(table, "."); } table = table.replace("\'", ""); table = table.replace("\"", ""); debug("table before return: " + table); return table; }
From source file:org.kawanfw.sql.jdbc.DatabaseMetaDataHttp.java
/** * Get the return type of a DatabaseMetaData method * /*w w w . ja v a2 s.c om*/ * @param methodName * the DatabaseMetaData method * @return the return type * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException */ private String getMethodReturnType(String methodName) throws ClassNotFoundException, SecurityException, NoSuchMethodException { Class<?> c = Class.forName("java.sql.DatabaseMetaData"); Method[] allMethods = c.getDeclaredMethods(); for (Method m : allMethods) { if (m.getName().endsWith(methodName)) { String returnType = m.getReturnType().toString(); if (returnType.startsWith("class ")) { returnType = StringUtils.substringAfter(returnType, "class "); } if (returnType.startsWith("interface ")) { returnType = StringUtils.substringAfter(returnType, "interface "); } return returnType; } } throw new NoSuchMethodException("DatabaseMetaData does not contain this method: " + methodName); }
From source file:org.kawanfw.sql.jdbc.PreparedStatementHttp.java
/** * Executes the given SQL statement, which may return multiple results. In * some (uncommon) situations, a single SQL statement may return multiple * result sets and/or update counts. Normally you can ignore this unless you * are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <P>//from w ww .java 2 s . co m * The <code>execute</code> method executes an SQL statement and indicates * the form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the * result, and <code>getMoreResults</code> to move to any subsequent * result(s). * * @param sql * any SQL statement * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no results * @exception SQLException * if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults */ @Override public boolean execute() throws SQLException { testIfClosed(); if (connectionHttp.isStatelessMode()) { if (!connectionHttp.getAutoCommit()) { throw new IllegalStateException( Tag.PRODUCT + "execute can\'t be executed when auto commit is off."); } } debug("PreparedStatementHttp.execute : " + sql); lastExecuteIsRaw = true; // Check that all parameters values are set ParametersUtil.checkParameters(statementHolder); statementHolder.setPreparedStatement(true); statementHolder.setExecuteUpdate(false); statementHolder.setJoinResultSetMetaData(connectionHttp.isJoinResultSetMetaData()); statementHolder.setZipResultSet(connectionHttp.isZipResultSet()); statementHolder.setFetchSize(fetchSize); statementHolder.setMaxRows(maxRows); statementHolder.setQueryTimeout(queryTimeout); statementHolder.setEscapeProcessing(escapeProcessingInt); // Reset the fields values rsFromExecute = null; updateCount = -1; // Send order to Server to SQL Executor JdbcHttpExecuteRawTransfer jdbcHttpExecuteRawTransfer = new JdbcHttpExecuteRawTransfer(connectionHttp, connectionHttp.getAuthenticationToken()); receiveFileFromExecute = jdbcHttpExecuteRawTransfer.getFileFromExecuteRaw(statementHolder); localFilesExecuteResult.add(receiveFileFromExecute); debug("getFileFromexecuteOnServer() : " + receiveFileFromExecute); boolean fileResultSet = super.isFileResultSet(receiveFileFromExecute); try { if (DEBUG) { String fileContent = FileUtils.readFileToString(receiveFileFromExecute); System.out.println(fileContent); } } catch (IOException e2) { throw new SQLException(e2); } if (fileResultSet) { // Transform the Result Set in String back to an Result Set // (emulated) rsFromExecute = new ResultSetHttp(connectionHttp, statementHolder, this, receiveFileFromExecute); return true; } else { BufferedReader bufferedReader = null; String line1 = null; try { bufferedReader = new BufferedReader(new FileReader(receiveFileFromExecute)); line1 = bufferedReader.readLine(); } catch (IOException e1) { throw new SQLException(e1); } finally { IOUtils.closeQuietly(bufferedReader); } String updateCountStr = StringUtils.substringAfter(line1, "getUpdateCount="); try { updateCount = Integer.parseInt(updateCountStr); } catch (NumberFormatException e) { throw new SQLException(Tag.PRODUCT_PRODUCT_FAIL + e.getMessage(), new IOException(e.getMessage(), e)); } return false; } }
From source file:org.kawanfw.sql.jdbc.ResultSetHttp.java
/** * Get the value of the column using the map inside the List * /* w ww . j a v a2 s .c o m*/ * @param columnIndex * the first column is 1, the second is 2, ... * @boolean if true, the returned value is a String ==> Parse it to remove * special characters ! * @return the value of the column using the map inside the List * * @throws SQLException */ private byte[] getBinaryValueOfList(int columnIndex) throws SQLException { String value = getValueOfList(columnIndex, false); if (value == null) { // Not sure what to do throw new SQLException("Column Index is out of bound: " + columnIndex); } byte[] bytes = null; // Check if we must get the byte array from an input stream if (value.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) { InputStream in = null; String remoteFile = StringUtils.substringAfter(value, TransportConverter.KAWANFW_BYTES_STREAM_FILE); // HACK if (!remoteFile.startsWith("/")) { remoteFile = "/" + remoteFile; } try { in = getInputStreamFromRemoteFile(remoteFile); bytes = getBytesFromInputStream(in); } finally { IOUtils.closeQuietly(in); } } else { bytes = TransportConverter.fromTransportFormatToBytes(value); } return bytes; }
From source file:org.kawanfw.sql.jdbc.ResultSetHttp.java
/** * Get the value of the column using the map inside the List * //w w w . j a va 2 s . c om * @param columnIndex * the first column is 1, the second is 2, ... * @boolean if true, the returned value is a String ==> Parse it to remove * special characters ! * @return the value of the column using the map inside the List * * @throws SQLException */ private InputStream getInputStreamOfMap(int columnIndex) throws SQLException { String value = getValueOfList(columnIndex, false); if (value == null) { // Not sure what to do throw new SQLException("Column Index is out of bound: " + columnIndex); } InputStream in = null; // Check if we must get the byte array from an input stream if (value.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) { String remoteFile = StringUtils.substringAfter(value, TransportConverter.KAWANFW_BYTES_STREAM_FILE); // HACK if (!remoteFile.startsWith("/")) { remoteFile = "/" + remoteFile; } in = getInputStreamFromRemoteFile(remoteFile); } else { byte[] bytes = TransportConverter.fromTransportFormatToBytes(value); in = new ByteArrayInputStream(bytes); } return in; }
From source file:org.kawanfw.sql.jdbc.ResultSetHttp.java
/** * Return the underlying file as a string * /* w w w . j av a 2 s . c o m*/ * @param s * the file address & name * @return the content as string * @throws SQLException */ private String getFileAsString(String s) throws SQLException { Reader reader = null; String remoteFile = StringUtils.substringAfter(s, TransportConverter.KAWANFW_BYTES_STREAM_FILE); try { reader = getReaderFromRemoteFile(remoteFile); if (reader == null) { return null; } StringWriter stringWriter = new StringWriter(); IOUtils.copy(reader, stringWriter); return stringWriter.toString(); } catch (Exception e) { throw new SQLException(e.getMessage(), e); } finally { IOUtils.closeQuietly(reader); } }