List of usage examples for java.lang String replaceFirst
public String replaceFirst(String regex, String replacement)
From source file:datawarehouse.CSVLoader.java
/** * Parse CSV file using OpenCSV library and load in given database table. * * @param csvFile Input CSV file//from w w w. jav a2s . c o m * @param tableName Database table name to import data * @param truncateBeforeLoad Truncate the table before inserting new * records. * @throws Exception */ public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad) throws Exception { CSVReader csvReader = null; if (null == this.connection) { throw new Exception("Not a valid connection."); } try { csvReader = new CSVReader(new FileReader(csvFile), this.seprator); } catch (Exception e) { e.printStackTrace(); throw new Exception("Error occured while executing file. " + e.getMessage()); } String[] headerRow = csvReader.readNext(); if (null == headerRow) { throw new FileNotFoundException( "No columns defined in given CSV file." + "Please check the CSV file format."); } String questionmarks = StringUtils.repeat("?,", headerRow.length); questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1); String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName); query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ",")); query = query.replaceFirst(VALUES_REGEX, questionmarks); System.out.println("Query: " + query); String[] nextLine; Connection con = null; PreparedStatement ps = null; try { con = this.connection; con.setAutoCommit(false); ps = con.prepareStatement(query); if (truncateBeforeLoad) { //delete data from table before loading csv con.createStatement().execute("DELETE FROM " + tableName); } final int batchSize = 1000; int count = 0; while ((nextLine = csvReader.readNext()) != null) { if (null != nextLine) { int index = 1; for (String string : nextLine) { //System.out.print(string + ": "); try { DateFormat format = new SimpleDateFormat("dd.mm.yyyy"); Date date = format.parse(string); ps.setDate(index++, new java.sql.Date(date.getTime())); //System.out.println("date"); } catch (ParseException | SQLException e) { try { Double income = parseDouble(string.replace(",", ".")); ps.setDouble(index++, income); //System.out.println("double"); } catch (NumberFormatException | SQLException err) { ps.setString(index++, string); //System.out.println("string"); } } } ps.addBatch(); } if (++count % batchSize == 0) { ps.executeBatch(); } } ps.executeBatch(); // insert remaining records con.commit(); } catch (Exception e) { con.rollback(); e.printStackTrace(); throw new Exception("Error occured while loading data from file to database." + e.getMessage()); } finally { if (null != ps) { ps.close(); } if (null != con) { con.close(); } csvReader.close(); } }
From source file:com.mycompany.securerest.auth.AuthenticationService.java
public boolean authenticate(String authCredentials) { if (null == authCredentials) return false; // header value format will be "Basic encodedstring" for Basic // authentication. Example "Basic YWRtaW46YWRtaW4=" final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); String usernameAndPassword = null; try {/* ww w. ja va2 s . c om*/ byte[] decodedBytes = Base64.decodeBase64(encodedUserPassword); usernameAndPassword = new String(decodedBytes, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); // we have fixed the userid and password as admin // call some UserService/LDAP here boolean authenticationStatus = "admin".equals(username) && "admin".equals(password); return authenticationStatus; }
From source file:net.morphbank.mbsvc3.webservices.RestfulService.java
protected String saveResponseXmlAsFile(String reqFileName, Object xmlDoc) { String fileName = reqFileName.replaceFirst("req", "resp"); // open a file try {/*from w ww . jav a2s . co m*/ FileOutputStream outFile = new FileOutputStream(filepath + fileName); PrintWriter out = new PrintWriter(outFile); XmlUtils.printXml(out, xmlDoc); out.close(); outFile.close(); } catch (Exception e) { e.printStackTrace(); } return fileName; }
From source file:org.obiba.magma.beans.BeanVariableValueSourceFactory.java
protected String unprefixName(String name) { return prefix != null ? name.replaceFirst(prefix, "") : name; }
From source file:com.stratio.cassandra.index.schema.ColumnMapperBigDecimal.java
/** {@inheritDoc} */ @Override//from w w w . j a va2 s . c o m public String indexValue(String name, Object value) { // Check not null if (value == null) { return null; } // Parse big decimal String svalue = value.toString(); BigDecimal bd; try { bd = new BigDecimal(value.toString()); } catch (NumberFormatException e) { String message = String.format("Field %s requires a base 10 decimal, but found \"%s\"", name, svalue); throw new IllegalArgumentException(message); } // Split integer and decimal part bd = bd.stripTrailingZeros(); String[] parts = bd.toPlainString().split("\\."); String integerPart = parts[0]; String decimalPart = parts.length == 1 ? "0" : parts[1]; if (integerPart.replaceFirst("-", "").length() > integerDigits) { throw new IllegalArgumentException("Too much digits in integer part"); } if (decimalPart.length() > decimalDigits) { throw new IllegalArgumentException("Too much digits in decimal part"); } BigDecimal complemented = bd.add(complement); String bds[] = complemented.toString().split("\\."); integerPart = bds[0]; decimalPart = bds.length == 2 ? bds[1] : "0"; integerPart = StringUtils.leftPad(integerPart, integerDigits + 1, '0'); return integerPart + "." + decimalPart; }
From source file:net.proest.librepilot.web.handler.ObjectHandler.java
public void handlePost(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); BufferedReader br = request.getReader(); String json = ""; while (br.ready()) { json += br.readLine();/*from w w w . j a v a 2 s .c o m*/ } System.out.println(json); json = json.replaceFirst("json=", ""); System.out.println(json); json = URLDecoder.decode(json, "utf-8"); System.out.println(json); System.out.println(); ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = mapper.readTree(json); out.println(actualObj.asText()); out.println(mapper.toString()); }
From source file:ca.sqlpower.wabit.report.selectors.ComboBoxSelector.java
public void setSourceKey(String sourceKey) { String oldSourceKey = this.sourceKey; if (sourceKey != null) { this.sourceKey = sourceKey.replaceFirst("\\$", "").replaceFirst("\\{", "").replaceFirst("\\}", ""); } else {/*from ww w .j a v a 2 s . co m*/ this.sourceKey = null; } if (!ObjectUtils.equals(this.sourceKey, oldSourceKey)) { Collection<Object> values = getPossibleValues(); if (values.size() > 0) { this.setSelectedValue(values.iterator().next()); } else { this.setSelectedValue(null); } firePropertyChange("sourceKey", oldSourceKey, this.sourceKey); fireSelectionChanged(); } }
From source file:ch.rgw.tools.StringTool.java
/** * Verknpft die Elemente eines String-Arrays mittels tren zu einem String * /*from w w w . ja v a 2 s . c o m*/ * @param arr * - String Array * @param tren * - Verbindingsstring * @return den verknpften String */ static public String join(final String[] arr, final String tren) { if ((arr == null) || (arr.length == 0)) { return ""; } StringBuffer res = new StringBuffer(100); for (int i = 0; i < arr.length; i++) { if (arr[i] == null) { continue; } res.append(arr[i]).append(tren); } String r2 = res.toString(); return r2.replaceFirst(tren + "$", ""); }
From source file:org.alfresco.bm.event.AbstractEventProcessor.java
@Override public void setBeanName(String beanName) { String eventName = beanName.replaceFirst(Event.EVENT_BEAN_PREFIX, ""); setEventName(eventName);//from w w w .j a v a2 s . c o m this.name = beanName; }
From source file:org.obiba.mica.file.search.FileFilterHelper.java
/** * Extract the entity identifier from base path. * * @param basePath// w ww . j a va 2 s . c o m * @param replace String to be removed at the beginning of base path * @return */ private String extractId(String basePath, String replace) { String p = basePath.replaceFirst(replace, ""); int idx = p.lastIndexOf('/'); return idx <= 0 ? p : p.substring(0, idx); }