List of usage examples for java.lang String replace
public String replace(CharSequence target, CharSequence replacement)
From source file:Main.java
public static void main(String[] args) { String str = "java2s.com"; System.out.println("string = " + str); CharSequence s1 = "j"; CharSequence s2 = "b"; String replaceStr = str.replace(s1, s2); System.out.println("new string = " + replaceStr); }
From source file:gda.util.PackageMaker.java
/** * @param args/*from ww w.j a v a 2 s . com*/ */ public static void main(String args[]) { String destDir = null; if (args.length == 0) return; String filename = args[0]; if (args.length > 1) destDir = args[1]; try { ClassParser cp = new ClassParser(filename); JavaClass classfile = cp.parse(); String packageName = classfile.getPackageName(); String apackageName = packageName.replace(".", File.separator); if (destDir != null) destDir = destDir + File.separator + apackageName; else destDir = apackageName; File destFile = new File(destDir); File existFile = new File(filename); File parentDir = new File(existFile.getAbsolutePath().substring(0, existFile.getAbsolutePath().lastIndexOf(File.separator))); String allFiles[] = parentDir.list(); Vector<String> selectedFiles = new Vector<String>(); String toMatch = existFile.getName().substring(0, existFile.getName().lastIndexOf(".")); for (int i = 0; i < allFiles.length; i++) { if (allFiles[i].startsWith(toMatch + "$")) selectedFiles.add(allFiles[i]); } FileUtils.copyFileToDirectory(existFile, destFile); Object[] filestoCopy = selectedFiles.toArray(); for (int i = 0; i < filestoCopy.length; i++) { FileUtils.copyFileToDirectory(new File((String) filestoCopy[i]), destFile); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java
public static void main(String[] args) { // TODO code application logic here String host = "10.49.28.3"; String port = "8081"; String reportName = "vencimientos"; String params = "feini=2016-09-30&fefin=2016-09-30"; String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}"; url = url.replace("{host}", host); url = url.replace("{port}", port); url = url.replace("{reportName}", reportName); url = url.replace("{params}", params); try {/* ww w .jav a 2 s . co m*/ CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password")); CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/pdf"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("vencimientos.pdf")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); if (Desktop.isDesktopSupported()) { File pdfFile = new File("vencimientos.pdf"); Desktop.getDesktop().open(pdfFile); } } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.gargoylesoftware.htmlunit.source.TestCaseCreator.java
/** * The entry point./*from ww w . j a v a 2 s. c o m*/ * * @param args the arguments * @throws IOException if an error occurs */ public static void main(final String[] args) throws IOException { if (args.length == 0) { System.out.println("HTML file location is not provided"); return; } final File file = new File(args[0]); if (!file.exists()) { System.out.println("File does not exist " + file.getAbsolutePath()); } System.out.println(" /**"); System.out.println(" * @throws Exception if an error occurs"); System.out.println(" */"); System.out.println(" @Test"); System.out.println(" @Alerts()"); System.out.println(" public void test() throws Exception {"); final List<String> lines = FileUtils.readLines(file, TextUtil.DEFAULT_CHARSET); for (int i = 0; i < lines.size(); i++) { final String line = lines.get(i); if (i == 0) { System.out.println(" final String html = \"" + line.replace("\"", "\\\"") + "\\n\""); } else { System.out.print(" + \"" + line.replace("\"", "\\\"") + "\\n\""); if (i == lines.size() - 1) { System.out.print(";"); } System.out.println(); } } System.out.println(" loadPageWithAlerts2(html);"); System.out.println(" }"); }
From source file:Server_socket.java
public static void main(String argv[]) throws Exception { int puerto = Integer.parseInt(argv[0]); //String username = argv[1]; //String password = argv[2]; String clientformat;//from www . ja v a2 s . c om String clientdata; String clientresult; String clientresource; String url_login = "http://localhost:3000/users/sign_in"; ServerSocket welcomeSocket = new ServerSocket(puerto); /*HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_login); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713'))); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String ret = EntityUtils.tostring(response.getEntity()); System.out.println(ret); */ while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientformat = inFromClient.readLine(); System.out.println("FORMAT: " + clientformat); BufferedReader inFromClient1 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientdata = inFromClient1.readLine(); System.out.println("DATA: " + clientdata); BufferedReader inFromClient2 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresult = inFromClient2.readLine(); System.out.println("RESULT: " + clientresult); BufferedReader inFromClient3 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresource = inFromClient3.readLine(); System.out.println("RESOURCE: " + clientresource); System.out.println("no pasas de aqui"); String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat; System.out.println(url); try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String stb = sb.toString(); System.out.println("estas aqui"); String output = null; String jsonText = stb; output = jsonText.replace("[", "").replace("]", ""); JSONObject json = new JSONObject(output); System.out.println(json.toString()); System.out.println("llegaste al final"); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); outToClient.writeBytes(json.toString()); } connectionSocket.close(); } }
From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorSimilarityWriter.java
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, SOMToolboxException { JSAPResult config = OptionFactory.parseResults(args, OptionFactory.OPTIONS_INPUT_SIMILARITY_COMPUTER); String inputVectorDistanceMatrix = config.getString("inputVectorDistanceMatrix"); String inputVectorFileName = config.getString("inputVectorFile"); int numNeighbours = config.getInt("numberNeighbours"); String outputFormat = config.getString("outputFormat"); InputVectorDistanceMatrix matrix = null; InputData data = new SOMLibSparseInputData(inputVectorFileName); if (StringUtils.isNotBlank(inputVectorDistanceMatrix)) { matrix = InputVectorDistanceMatrix.initFromFile(inputVectorDistanceMatrix); } else {/* w ww . java 2s. co m*/ String metricName = config.getString("metric"); DistanceMetric metric = AbstractMetric.instantiate(metricName); matrix = new LeightWeightMemoryInputVectorDistanceMatrix(data, metric); } String outputFileName = config.getString("output"); PrintWriter w = FileUtils.openFileForWriting("Similarity File", outputFileName); if (outputFormat.equals("SAT-DB")) { // find feature type String type = ""; if (inputVectorFileName.endsWith(".rh") || inputVectorFileName.endsWith(".rp") || inputVectorFileName.endsWith(".ssd")) { type = "_" + inputVectorFileName.substring(inputVectorFileName.lastIndexOf(".") + 1); } w.println("INSERT INTO `sat_track_similarity_ifs" + type + "` (`TRACKID`, `SIMILARITYCOUNT`, `SIMILARITYIDS`) VALUES "); } int numVectors = matrix.numVectors(); // numVectors = 10; // for testing StdErrProgressWriter progress = new StdErrProgressWriter(numVectors, "Writing similarities for vector ", 1); for (int i = 0; i < numVectors; i++) { int[] nearest = matrix.getNNearest(i, numNeighbours); if (outputFormat.equals("SAT-DB")) { w.print(" (" + i + " , NULL, '"); for (int j = 0; j < nearest.length; j++) { String label = data.getLabel(nearest[j]); w.print(label.replace(".mp3", "")); // strip ending if (j + 1 < nearest.length) { w.print(","); } else { w.print("')"); } } if (i + 1 < numVectors) { w.print(","); } } else { w.print(data.getLabel(i) + ","); for (int j = 0; j < nearest.length; j++) { w.print(data.getLabel(nearest[j])); if (j + 1 < nearest.length) { w.print(","); } } } w.println(); w.flush(); progress.progress(); } if (outputFormat.equals("SAT-DB")) { w.print(";"); } w.flush(); w.close(); }
From source file:org.jboss.teiid.quickstart.PortfolioClient.java
public static void main(String[] args) throws URISyntaxException, UnsupportedEncodingException { if (args.length == 4) { HOSTNAME = args[0];// www . ja va2 s . c om HOSTPORT = args[1]; USERNAME = args[2]; PASSWORD = args[3]; } for (int i = 0; i < apilist.length; i++) { String api = apilist[i]; api = api.replace("${hostname}", HOSTNAME); api = api.replace("${port}", HOSTPORT); apis[i] = api; } PortfolioClient client = new PortfolioClient(); client.jaxrsClient(); client.resteasyClient(); client.resteasyHttpBackendClient(); }
From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java
public static void main(String[] args) { try {//w w w.j a v a2 s. c o m // String input = args[0]; String input = "../../data/data_totale.csv"; String csvString = FileUtils.readFile(input, Charset.defaultCharset()); csvString.replace("\"\"\"", "\""); JSONArray adjustedTimeAndTipiSpecifici = new CamelizeSomeFieldsAndExtractInformazioniStoricheDates() .adjustTimeAndTipiSpecifici(csvString); String adjustedTimeAndTipiSpecificiString = adjustedTimeAndTipiSpecifici.toString(); System.out.println(adjustedTimeAndTipiSpecificiString); FileUtils.writeToFile(adjustedTimeAndTipiSpecificiString, "../data_totale_camelized_some_fields.json"); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
From source file:com.daoke.mobileserver.test.TestHttps.java
public static void main(String args[]) { /*/*ww w. j ava2 s .c o m*/ AtomicInteger a = new AtomicInteger(); a.getAndIncrement();*/ String str = "version,ordertype,username,outerno,companyno,insuredperson,plcstartdate,plcenddate,licenseno,nolicenseflag,ownername,owneridno,ownercerttype,ownercertno,citycode,cardno,firstregisterdate,vehiclemodelname,vehicleid,vehicleframeno,engineno,vehicleinvoiceno,vehicleinvoicedate,runcardcertificatedate,forcebegindate,bizbegindate,taxvehicletype,fueltype,specialcarflag,specialcardate,persontaxcode,taxticketno,taxtickettype,taxbureauname,settledaddress,vehicleseats,averagemile,trafficviolation,bizquestion,bizanswer,forcequestion,forceanswer,vehiclecode,vehiclecodename,sessionid,trafficinsurance,traveltax,remark1,remark2,remark3,remark4,remark5,remark6,remark7,remark8,remark9,remark10,remark11,remark12,remark13,remark14,remark15,step,linkInfo_name,linkInfo_mobile,linkInfo_address,linkInfo_invoice,linkInfo_zipcode,linkInfo_email,linkInfo_paytype,linkInfo_realpaymode,insurInfo_name,insurInfo_certtype,insurInfo_certno,insurInfo_sex,insurInfo_birth,insurInfo_email,aplInfo_name,aplInfo_certtype,aplInfo_certno,aplInfo_sex,aplInfo_birth,aplInfo_email,businesspremium,forcepremium,vehicletaxamount,realpremium,totalremium,configbeforejudge"; String[] strs = str.split(","); for (String str1 : strs) { String str2 = str1.replace(str1.charAt(0), (char) (str1.charAt(0) - 32)); System.out.print("ejsinoFormModel.get" + str2 + "(),"); } /* Date a = new Date(123); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(a); System.out.println(a.getTime()); System.out.println( sdf.format(a));*/ /* TestHttps test = new TestHttps(); try { String resp = test.doPost("https://192.168.11.93:1500/lua",null,DEFAULT_CHARSET,2000,1000); System.out.println(resp); } catch (Exception e) { e.printStackTrace(); }*/ }
From source file:com.util.finalProy.java
/** * @param args the command line arguments *///from ww w .j a v a 2s . co m public static void main(String[] args) throws JSONException { // TODO code application logic her System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println(sb.toString()); System.out.println( "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); System.out.println("objeto normal 1 " + dataJson.toString()); // // System.out.println( "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); System.out.println("new json string" + jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); System.out.println("el objeto simple json es " + objJson2.toString()); System.out.println( "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); System.out.println( "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("id")); System.out.println( "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); Account account = gson.fromJson(objJson3.toString(), Account.class); System.out.println(account.getFirst_name()); System.out.println(account.getCreation()); }